file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT /* Coded with ♥ by ██████╗░███████╗███████╗██╗  ░██╗░░░░░░░██╗░█████╗░███╗░░██╗██████╗░███████╗██████╗░██╗░░░░░░█████╗░███╗░░██╗██████╗░ ██╔══██╗██╔════╝██╔════╝██║  ░██║░░██╗░░██║██╔══██╗████╗░██║██╔══██╗██╔════╝██╔══██╗██║░░░░░██╔══██╗████╗░██║██╔══██╗ ██║░░██║█████╗░░█████╗░░██║  ░╚██╗████╗██╔╝██║░░██║██╔██╗██║██║░░██║█████╗░░██████╔╝██║░░░░░███████║██╔██╗██║██║░░██║ ██║░░██║██╔══╝░░██╔══╝░░██║  ░░████╔═████║░██║░░██║██║╚████║██║░░██║██╔══╝░░██╔══██╗██║░░░░░██╔══██║██║╚████║██║░░██║ ██████╔╝███████╗██║░░░░░██║  ░░╚██╔╝░╚██╔╝░╚█████╔╝██║░╚███║██████╔╝███████╗██║░░██║███████╗██║░░██║██║░╚███║██████╔╝ ╚═════╝░╚══════╝╚═╝░░░░░╚═╝  ░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚══╝╚═════╝░╚══════╝╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚══╝╚═════╝░ https://defi.sucks */ pragma solidity >=0.8.4 <0.9.0; import '@openzeppelin/contracts/utils/math/Math.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import './Governable.sol'; import './interfaces/IVestingWallet.sol'; contract VestingWallet is IVestingWallet, Governable { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet internal _vestedTokens; EnumerableSet.AddressSet internal _beneficiaries; mapping(address => EnumerableSet.AddressSet) internal _tokensPerBeneficiary; // beneficiary => [tokens] /// @inheritdoc IVestingWallet mapping(address => uint256) public override totalAmountPerToken; // token => amount /// @inheritdoc IVestingWallet mapping(address => mapping(address => Benefit)) public override benefits; // token => beneficiary => benefit constructor(address _governance) Governable(_governance) {} // Views /// @inheritdoc IVestingWallet function releaseDate(address _token, address _beneficiary) external view override returns (uint256) { Benefit memory _benefit = benefits[_token][_beneficiary]; return _benefit.startDate + _benefit.duration; } /// @inheritdoc IVestingWallet function releasableAmount(address _token, address _beneficiary) external view override returns (uint256) { Benefit memory _benefit = benefits[_token][_beneficiary]; return _releasableSchedule(_benefit) - _benefit.released; } /// @inheritdoc IVestingWallet function getBeneficiaries() external view override returns (address[] memory) { return _beneficiaries.values(); } /// @inheritdoc IVestingWallet function getTokens() external view override returns (address[] memory) { return _vestedTokens.values(); } /// @inheritdoc IVestingWallet function getTokensOf(address _beneficiary) external view override returns (address[] memory) { return _tokensPerBeneficiary[_beneficiary].values(); } // Methods /// @inheritdoc IVestingWallet function addBenefit( address _beneficiary, uint256 _startDate, uint256 _duration, address _token, uint256 _amount ) external override onlyGovernance { _addBenefit(_beneficiary, _startDate, _duration, _token, _amount); totalAmountPerToken[_token] += _amount; IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); } /// @inheritdoc IVestingWallet function addBenefits( address _token, address[] calldata __beneficiaries, uint256[] calldata _amounts, uint256 _startDate, uint256 _duration ) external override onlyGovernance { uint256 _length = __beneficiaries.length; if (_length != _amounts.length) revert WrongLengthAmounts(); uint256 _vestedAmount; for (uint256 _i; _i < _length; _i++) { _addBenefit(__beneficiaries[_i], _startDate, _duration, _token, _amounts[_i]); _vestedAmount += _amounts[_i]; } totalAmountPerToken[_token] += _vestedAmount; IERC20(_token).safeTransferFrom(msg.sender, address(this), _vestedAmount); } /// @inheritdoc IVestingWallet function removeBenefit(address _token, address _beneficiary) external override onlyGovernance { _removeBenefit(_token, _beneficiary); } /// @inheritdoc IVestingWallet function removeBeneficiary(address _beneficiary) external override onlyGovernance { while (_tokensPerBeneficiary[_beneficiary].length() > 0) { _removeBenefit(_tokensPerBeneficiary[_beneficiary].at(0), _beneficiary); } } /// @inheritdoc IVestingWallet function release(address _token) external override { _release(_token, msg.sender); } /// @inheritdoc IVestingWallet function release(address _token, address _beneficiary) external override { _release(_token, _beneficiary); } /// @inheritdoc IVestingWallet function release(address[] calldata _tokens) external override { _release(_tokens, msg.sender); } /// @inheritdoc IVestingWallet function release(address[] calldata _tokens, address _beneficiary) external override { _release(_tokens, _beneficiary); } /// @inheritdoc IVestingWallet function releaseAll() external override { _releaseAll(msg.sender); } /// @inheritdoc IVestingWallet function releaseAll(address _beneficiary) external override { _releaseAll(_beneficiary); } /// @inheritdoc IDustCollector function sendDust(address _token) external override onlyGovernance { uint256 _amount; _amount = IERC20(_token).balanceOf(address(this)) - totalAmountPerToken[_token]; IERC20(_token).safeTransfer(governance, _amount); emit DustSent(_token, _amount, governance); } // Internal function _addBenefit( address _beneficiary, uint256 _startDate, uint256 _duration, address _token, uint256 _amount ) internal { if (_tokensPerBeneficiary[_beneficiary].contains(_token)) { _release(_token, _beneficiary); } _beneficiaries.add(_beneficiary); _vestedTokens.add(_token); _tokensPerBeneficiary[_beneficiary].add(_token); Benefit storage _benefit = benefits[_token][_beneficiary]; _benefit.startDate = _startDate; _benefit.duration = _duration; uint256 pendingAmount = _benefit.amount - _benefit.released; _benefit.amount = _amount + pendingAmount; _benefit.released = 0; emit BenefitAdded(_token, _beneficiary, _benefit.amount, _startDate, _startDate + _duration); } function _release(address _token, address _beneficiary) internal { Benefit storage _benefit = benefits[_token][_beneficiary]; uint256 _releasable = _releasableSchedule(_benefit) - _benefit.released; if (_releasable == 0) { return; } _benefit.released += _releasable; totalAmountPerToken[_token] -= _releasable; if (_benefit.released == _benefit.amount) { _deleteBenefit(_token, _beneficiary); } IERC20(_token).safeTransfer(_beneficiary, _releasable); emit BenefitReleased(_token, _beneficiary, _releasable); } function _release(address[] calldata _tokens, address _beneficiary) internal { uint256 _length = _tokens.length; for (uint256 _i; _i < _length; _i++) { _release(_tokens[_i], _beneficiary); } } function _releaseAll(address _beneficiary) internal { address[] memory _tokens = _tokensPerBeneficiary[_beneficiary].values(); uint256 _length = _tokens.length; for (uint256 _i; _i < _length; _i++) { _release(_tokens[_i], _beneficiary); } } function _removeBenefit(address _token, address _beneficiary) internal { _release(_token, _beneficiary); Benefit storage _benefit = benefits[_token][_beneficiary]; uint256 _transferToOwner = _benefit.amount - _benefit.released; totalAmountPerToken[_token] -= _transferToOwner; if (_transferToOwner != 0) { IERC20(_token).safeTransfer(msg.sender, _transferToOwner); } _deleteBenefit(_token, _beneficiary); emit BenefitRemoved(_token, _beneficiary, _transferToOwner); } function _releasableSchedule(Benefit memory _benefit) internal view returns (uint256) { uint256 _timestamp = block.timestamp; uint256 _start = _benefit.startDate; uint256 _duration = _benefit.duration; uint256 _totalAllocation = _benefit.amount; if (_timestamp <= _start) { return 0; } else { return Math.min(_totalAllocation, (_totalAllocation * (_timestamp - _start)) / _duration); } } function _deleteBenefit(address _token, address _beneficiary) internal { delete benefits[_token][_beneficiary]; _tokensPerBeneficiary[_beneficiary].remove(_token); if (_tokensPerBeneficiary[_beneficiary].length() == 0) { _beneficiaries.remove(_beneficiary); } if (totalAmountPerToken[_token] == 0) { _vestedTokens.remove(_token); } } } // SPDX-License-Identifier: MIT pragma solidity ^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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // 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 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; 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './interfaces/IGovernable.sol'; abstract contract Governable is IGovernable { /// @inheritdoc IGovernable address public override governance; /// @inheritdoc IGovernable address public override pendingGovernance; constructor(address _governance) { if (_governance == address(0)) revert NoGovernanceZeroAddress(); governance = _governance; } /// @inheritdoc IGovernable function setGovernance(address _governance) external override onlyGovernance { pendingGovernance = _governance; emit GovernanceProposal(_governance); } /// @inheritdoc IGovernable function acceptGovernance() external override onlyPendingGovernance { governance = pendingGovernance; delete pendingGovernance; emit GovernanceSet(governance); } /// @notice Functions with this modifier can only be called by governance modifier onlyGovernance() { if (msg.sender != governance) revert OnlyGovernance(); _; } /// @notice Functions with this modifier can only be called by pendingGovernance modifier onlyPendingGovernance() { if (msg.sender != pendingGovernance) revert OnlyPendingGovernance(); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './IDustCollector.sol'; /// @title VestingWallet contract /// @notice Handles the vesting of ERC20 tokens for multiple beneficiaries interface IVestingWallet is IDustCollector { // Errors /// @notice Throws when the length of the amounts do not match error WrongLengthAmounts(); // Events /// @notice Emitted when a benefit is successfully added event BenefitAdded(address indexed token, address indexed beneficiary, uint256 amount, uint256 startDate, uint256 releaseDate); /// @notice Emitted when a benefit is successfully removed event BenefitRemoved(address indexed token, address indexed beneficiary, uint256 removedAmount); /// @notice Emitted when a benefit is successfully released event BenefitReleased(address indexed token, address indexed beneficiary, uint256 releasedAmount); // Structs /// @notice Stores benefit information by each beneficiary and token pair struct Benefit { uint256 amount; // Amount of vested token for the inputted beneficiary uint256 startDate; // Timestamp at which the benefit starts to take effect uint256 duration; // Seconds to unlock the full benefit uint256 released; // The amount of vested tokens already released } // Views /// @notice Lists users with an ongoing benefit /// @return _beneficiaries List of beneficiaries function getBeneficiaries() external view returns (address[] memory _beneficiaries); /// @notice Lists all the tokens that are currently vested /// @return _tokens List of vested tokens function getTokens() external view returns (address[] memory _tokens); /// @notice Lists the current vested tokens for the given address /// @param _beneficiary Address of the beneficiary /// @return _tokens List of vested tokens function getTokensOf(address _beneficiary) external view returns (address[] memory _tokens); /// @notice Returns the benefit data for a given token and beneficiary /// @param _token Address of ERC20 token to be vested /// @param _beneficiary Address of the beneficiary /// @return amount Amount of vested token for the inputted beneficiary /// @return startDate Timestamp at which the benefit starts to take effect /// @return duration Seconds to unlock the full benefit /// @return released The amount of vested tokens already released function benefits(address _token, address _beneficiary) external view returns ( uint256 amount, uint256 startDate, uint256 duration, uint256 released ); /// @notice Returns the end date of a vesting period /// @param _token Address of ERC20 vested token /// @param _beneficiary Address of the beneficiary /// @return _releaseDate The timestamp at which benefit will be fully released. function releaseDate(address _token, address _beneficiary) external view returns (uint256 _releaseDate); /// @notice Returns the claimable amount of a vested token for a specific beneficiary /// @dev If the vesting period did not end, it returns a proportional claimable amount /// @dev If the vesting period is over, it returns the complete vested amount /// @param _token Address of ERC20 token to be vested /// @param _beneficiary Address of the beneficiary /// @return _claimableAmount The amount of the vested token the beneficiary can claim at this point in time function releasableAmount(address _token, address _beneficiary) external view returns (uint256 _claimableAmount); /// @notice Returns the total amount of the given vested token across all beneficiaries /// @param _token Address of ERC20 token to be vested /// @return _totalAmount The total amount of requested tokens function totalAmountPerToken(address _token) external view returns (uint256 _totalAmount); // Methods /// @notice Creates a vest for a given beneficiary. /// @dev It will claim all previous benefits. /// @param _beneficiary Address of the beneficiary /// @param _startDate Timestamp at which the benefit starts to take effect /// @param _duration Seconds to unlock the full benefit /// @param _token Address of ERC20 token to be vested /// @param _amount Amount of vested token for the inputted beneficiary function addBenefit( address _beneficiary, uint256 _startDate, uint256 _duration, address _token, uint256 _amount ) external; /// @notice Creates benefits for a group of beneficiaries /// @param _token Address of ERC20 token to be vested /// @param _beneficiaries Addresses of the beneficiaries /// @param _amounts Amounts of vested token for each beneficiary /// @param _startDate Timestamp at which the benefit starts to take effect /// @param _duration Seconds to unlock the full benefit function addBenefits( address _token, address[] memory _beneficiaries, uint256[] memory _amounts, uint256 _startDate, uint256 _duration ) external; /// @notice Removes a given benefit /// @notice Releases the claimable balance and transfers the pending benefit to governance /// @param _token Address of ERC20 token to be vested /// @param _beneficiary Address of the beneficiary function removeBenefit(address _token, address _beneficiary) external; /// @notice Removes all benefits from a given beneficiary /// @notice Releases the claimable balances and transfers the pending benefits to governance /// @param _beneficiary Address of the beneficiary function removeBeneficiary(address _beneficiary) external; /// @notice Releases a token in its correspondent amount to the function caller /// @param _token Address of ERC20 token to be vested function release(address _token) external; /// @notice Releases a token in its correspondent amount to a particular beneficiary /// @param _token Address of ERC20 token to be vested /// @param _beneficiary Address of the beneficiary function release(address _token, address _beneficiary) external; /// @notice Releases a list of tokens in their correspondent amounts to the function caller /// @param _tokens List of ERC20 token to be vested function release(address[] memory _tokens) external; /// @notice Releases a list of tokens in their correspondent amounts to a particular beneficiary /// @param _tokens List of ERC20 token to be vested /// @param _beneficiary Address of the beneficiary function release(address[] memory _tokens, address _beneficiary) external; /// @notice Releases all tokens in their correspondent amounts to the function caller function releaseAll() external; /// @notice Releases all tokens in their correspondent amounts to a particular beneficiary /// @param _beneficiary Address of the beneficiary function releaseAll(address _beneficiary) external; } // 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.4 <0.9.0; /// @title Governable contract /// @notice Manages the governance role interface IGovernable { // Events /// @notice Emitted when pendingGovernance accepts to be governance /// @param _governance Address of the new governance event GovernanceSet(address _governance); /// @notice Emitted when a new governance is proposed /// @param _pendingGovernance Address that is proposed to be the new governance event GovernanceProposal(address _pendingGovernance); // Errors /// @notice Throws if the caller of the function is not governance error OnlyGovernance(); /// @notice Throws if the caller of the function is not pendingGovernance error OnlyPendingGovernance(); /// @notice Throws if trying to set governance to zero address error NoGovernanceZeroAddress(); // Variables /// @notice Stores the governance address /// @return _governance The governance addresss function governance() external view returns (address _governance); /// @notice Stores the pendingGovernance address /// @return _pendingGovernance The pendingGovernance addresss function pendingGovernance() external view returns (address _pendingGovernance); // Methods /// @notice Proposes a new address to be governance /// @param _governance The address of the user proposed to be the new governance function setGovernance(address _governance) external; /// @notice Changes the governance from the current governance to the previously proposed address function acceptGovernance() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './IBaseErrors.sol'; interface IDustCollector is IBaseErrors { /// @notice Emitted when dust is sent /// @param _to The address which wil received the funds /// @param _token The token that will be transferred /// @param _amount The amount of the token that will be transferred event DustSent(address _token, uint256 _amount, address _to); /// @notice Allows an authorized user to transfer the tokens or eth that may have been left in a contract /// @param _token The token that will be transferred function sendDust(address _token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; interface IBaseErrors { /// @notice Throws if a variable is assigned to the zero address error ZeroAddress(); }
@inheritdoc IVestingWallet
function removeBenefit(address _token, address _beneficiary) external override onlyGovernance { _removeBenefit(_token, _beneficiary); }
13,862,287
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; using Strings for uint; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; string domainName; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( isNodeExist(msg.sender, nodeIndex) || _isAdmin(msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender), "Sender is not permitted to call this function" ); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, params.domainName, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { nodes[nodeIndex].domainName = domainName; } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return nodes[nodeIndex].domainName; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, string memory domainName, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId, domainName: domainName })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); (partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain); if (numberOfNodes == 0) { revert("Bad schain type"); } } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin { schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 5; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenLaunchLocker.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenLaunchLocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; import "./PartialDifferences.sol"; /** * @title TokenLaunchLocker * @dev This contract manages lockers applied to the launch process. */ contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Allows the Owner to set the maximum number of validators that a single delegator can delegate to./
function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; }
401,034
./full_match/43113/0xe9204B935f32829EE52A8f6D158609bF25F1813D/sources/airdrop.sol
用户访问 临时授权领取(货币地址) 查询当前用户是否已领取过 授权 (访问者,可以用多少) 转移资产 (从所有者,到访问者,资产数量) 把领取的这个用户存入数组
function distribute(IERC20 token) public { require(!contains(msg.sender), "You may not repeat recipients."); require( token.approve(msg.sender, 10), "You can assign the assets have been exhausted." ); require( token.transferFrom(owner(), msg.sender, 10), "You can assign the assets have been exhausted." ); saveUsers(msg.sender); }
7,132,802
./partial_match/42/0xC79bF13a7199867E6349287e90Ed76D645399705/sources/FlashLender.sol
The fee to be charged for a given loan. token The loan currency. amount The amount of tokens lent. return The amount of `token` to be charged for the loan, on top of the returned principal./
function flashFee(address token, uint256 amount) external view override returns (uint256) { require(supportedTokens[token], "FlashLender: Unsupported currency"); return _flashFee(token, amount); }
3,398,822
// File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is 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; } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) 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 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // File: contracts/satoshi.sol /** *Submitted for verification at BscScan.com on 2021-12-06 */ pragma solidity ^0.8.0; contract SatoshiViralStake is Ownable { using SafeMath for uint256; // stakeToken address (SATs) // 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984 : UNI IERC20 public stakeToken; // rewardToken address (WBTC) // 0x110a13FC3efE6A245B50102D2d79B3E76125Ae83 : USDT IERC20 public rewardToken; // maxStakableToken : available stakable token maximan amount // first totalSupply, second can be set uint256 public maxStakeableToken; // minStakableToken : available stakable token minimam amount // first 1e18, second can be set uint256 public minimumStakeToken; // total amount of unstaked token uint256 public totalUnStakedToken; // total amount of staked token uint256 public totalStakedToken; // total amount of claimed reward token uint256 public totalClaimedRewardToken; // total stakers : user array uint256 public totalStakers; // percent divider : proportion uint256 public percentDivider; // duration : lock time uint256 public Duration = 3600 * 24 * 7 seconds; // bonus : how much reward can be get uint256 public Bonus = 1; // Stake struct Stake { uint256 unstaketime; // when unstake is available uint256 staketime; // when token is staked uint256 amount; // amount of staked token uint256 reward; // amount of ward (total) uint256 availableUnstakedAmount; uint256 availableUnclaimedReward; bool withdrawn; // status : reward is taken bool unstaked; // status : stakeToken is unstaked } struct User { uint256 totalStakedTokenUser; // how much token did user stake uint256 totalUnstakedTokenUser; // how much token did user unstake uint256 totalClaimedRewardTokenUser; // how much reward did user claim uint256 stakeCount; // how many times did user stake bool alreadyExists; // is this user already exist? } // user array : addreess => user mapping(address => User) public Stakers; // staker id array : id => address mapping(uint256 => address) public StakersID; // record of stakers : address => id => Stake mapping(address => mapping(uint256 => Stake)) public stakersRecord; // STAKE event event STAKE(address Staker, uint256 amount); // UNSTAKE event event UNSTAKE(address Staker, uint256 amount); // CLAIM event event CLAIM(address Staker, uint256 amount); // constructor constructor(address stakingtoken, address rewardingtoken) { // stakingtoken: staking token address (SATs) // rewardtoken: reward token address (WBTC) // get IERC20 stakeToken stakeToken = IERC20(stakingtoken); // get IERC20 rewardToken rewardToken = IERC20(rewardingtoken); // available maximum amount of stakeToken maxStakeableToken = stakeToken.totalSupply(); // available minimum amount of stakeToken minimumStakeToken = 0; // percent divider: proportion percentDivider = 1e2; } // stake function function stake(uint256 amount) public { require(amount >= minimumStakeToken, "stake more than minimum amount"); // insert stakers to list if (!Stakers[msg.sender].alreadyExists) { Stakers[msg.sender].alreadyExists = true; StakersID[totalStakers] = msg.sender; totalStakers++; } // transfer stakeToken (SATs) to smart contract stakeToken.transferFrom(msg.sender, address(this), amount); // get stakeCount of staker uint256 index = Stakers[msg.sender].stakeCount; // add amount to totalStakedTokenUser of staker Stakers[msg.sender].totalStakedTokenUser = Stakers[msg.sender] .totalStakedTokenUser .add(amount); // add amount to totalStakedToken => smart contract totalStakedToken totalStakedToken = totalStakedToken.add(amount); // create new record with staketime as block.timestamp stakersRecord[msg.sender][index].staketime = block.timestamp; // set unstake time of new record stakersRecord[msg.sender][index].unstaketime = block.timestamp.add( Duration ); // set amount => staking amount stakersRecord[msg.sender][index].amount = amount; // set reward => claiming reward // amount * Bonus / percentDivider // percentDivider is constant stakersRecord[msg.sender][index].reward = GetRewardOf(amount); stakersRecord[msg.sender][index].availableUnstakedAmount = amount; stakersRecord[msg.sender][index].availableUnclaimedReward = GetRewardOf( amount ); stakersRecord[msg.sender][index].unstaked = false; stakersRecord[msg.sender][index].withdrawn = false; // increase stakeCount of User => User[stakeCount] ++ Stakers[msg.sender].stakeCount++; // emite STAKE emit STAKE(msg.sender, amount); } // unstake function function unstake(uint256 amount) public { // check the index of stake token that unstaked before // require( // amount > GetMaxUnstakeAmount(), // "amount must be less than available max unstake amount" // ); uint256 sendAmount = amount; for (uint256 index; index < Stakers[msg.sender].stakeCount; index++) { if (stakersRecord[msg.sender][index].unstaked || amount == 0) { continue; } if ( stakersRecord[msg.sender][index].unstaketime >= block.timestamp ) { continue; } if ( stakersRecord[msg.sender][index].availableUnstakedAmount > amount ) { stakersRecord[msg.sender][index].availableUnstakedAmount = stakersRecord[msg.sender][index].availableUnstakedAmount - amount; amount = 0; } else { amount = amount - stakersRecord[msg.sender][index].availableUnstakedAmount; stakersRecord[msg.sender][index].availableUnstakedAmount = 0; stakersRecord[msg.sender][index].unstaked = true; } } // transfer stakeToken to staker => from smart contract to staker stakeToken.transfer(msg.sender, sendAmount); // add totalUnStakedToken amount totalUnStakedToken = totalUnStakedToken.add(sendAmount); // add totalUnstakedTokenUser of Staker amount Stakers[msg.sender].totalUnstakedTokenUser = Stakers[msg.sender] .totalUnstakedTokenUser .add(sendAmount); // emit UNSTAKE emit UNSTAKE(msg.sender, sendAmount); } // claim function function claim(uint256 amount) public { // check the index of stake token that unstaked before // require( // amount > GetMaxUnclaimedAmount(), // "amount must be less than available max unclaimed amount" // ); uint256 sendReward = amount; for (uint256 index; index < Stakers[msg.sender].stakeCount; index++) { if (stakersRecord[msg.sender][index].withdrawn || amount == 0) { continue; } if ( stakersRecord[msg.sender][index].unstaketime >= block.timestamp ) { continue; } if ( stakersRecord[msg.sender][index].availableUnclaimedReward > amount ) { stakersRecord[msg.sender][index].availableUnclaimedReward = stakersRecord[msg.sender][index].availableUnclaimedReward - amount; amount = 0; } else { amount = amount - stakersRecord[msg.sender][index].availableUnclaimedReward; stakersRecord[msg.sender][index].availableUnclaimedReward = 0; stakersRecord[msg.sender][index].withdrawn = true; } } // give rewardToken to staker => send rewardToken from smart contrac to staker rewardToken.transfer(msg.sender, sendReward); // add totalRewardToken amount totalClaimedRewardToken = totalClaimedRewardToken.add(sendReward); // add totalClaimUser of Staker amount Stakers[msg.sender].totalClaimedRewardTokenUser = Stakers[msg.sender] .totalClaimedRewardTokenUser .add(sendReward); // emit CLAIM emit CLAIM(msg.sender, sendReward); } // SetStakeLimits with min value and max value function SetStakeLimits(uint256 _min, uint256 _max) external onlyOwner { minimumStakeToken = _min; maxStakeableToken = _max; } // set StakeDuration function SetStakeDuration(uint256 newDuration) external onlyOwner { Duration = newDuration; } // set StakeBonus function SetStakeBonus(uint256 newBonus) external onlyOwner { Bonus = newBonus; } // set PercentDivider function SetPercentDivider(uint256 newPercentDivider) external onlyOwner { percentDivider = newPercentDivider; } // get StakeToken balance function GetStakeTokenBalanceOf(address account) public view returns (uint256) { uint256 stakeTokenBalance = stakeToken.balanceOf(account); return stakeTokenBalance; } // get RewardToken balance function GetRewardTokenBalanceOf(address account) public view returns (uint256) { uint256 rewardTokenBalance = rewardToken.balanceOf(account); return rewardTokenBalance; } // get Staking List of Staker function GetStakingListOf(address user) public view returns (Stake[] memory) { uint256 stakeCount = Stakers[user].stakeCount; Stake[] memory stakingList = new Stake[](stakeCount); for (uint256 i = 0; i < stakeCount; i++) { Stake storage staking = stakersRecord[user][i]; stakingList[i] = staking; } return stakingList; } // get Staking List of Staker function GetRewardOf(uint256 amount) public view returns (uint256 reward) { return amount.div(totalStakedToken).mul(1e2).mul(1e9); } // get Available Unstake Token Amount function GetMaxUnstakeAmount(address user) public view returns (uint256 reward) { uint256 maxUnstakeAmount; for (uint256 index; index < Stakers[user].stakeCount; index++) { if (!stakersRecord[user][index].unstaked) { if (stakersRecord[user][index].unstaketime < block.timestamp) { maxUnstakeAmount = maxUnstakeAmount.add( stakersRecord[user][index].availableUnstakedAmount ); } } } return maxUnstakeAmount; } // get Available Unstake Token Amount function GetMaxUnclaimedAmount(address user) public view returns (uint256 reward) { uint256 maxUnclaimedReward; for (uint256 index; index < Stakers[user].stakeCount; index++) { if (!stakersRecord[user][index].withdrawn) { if (stakersRecord[user][index].unstaketime < block.timestamp) { maxUnclaimedReward = maxUnclaimedReward.add( stakersRecord[user][index].availableUnclaimedReward ); } } } return maxUnclaimedReward; } function GetTimestamp() public view returns (uint256 time) { return block.timestamp; } }
get StakeToken balance
function GetStakeTokenBalanceOf(address account) public view returns (uint256) { uint256 stakeTokenBalance = stakeToken.balanceOf(account); return stakeTokenBalance; }
1,730,441
pragma solidity ^0.4.15; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Returns total number of transactions after filers are applied. pending Include pending transactions. executed Include executed transactions. return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; }
10,044,344
/* Implementation of contract EulerRoot */ pragma ton-solidity >= 0.32.0; pragma AbiHeader expire; pragma AbiHeader pubkey; import "./IEulerRoot.sol"; import "EulerProblem.sol"; import "EulerUser.sol"; import "RecoverablePubkey.sol.gen"; contract EulerRoot is IEulerRoot, RecoverablePubkey { uint64 constant EXN_AUTH_FAILED = 100 ; uint64 constant EXN_NOT_ENOUGH_VALUE = 101 ; /// @dev This event is emitted everytime a user solves a problem event ProblemSolved( uint32 problem, uint256 pubkey ); // The owner of this contract, who can create new EulerProblem // contracts uint256 g_owner ; // The code of EulerProblem contracts TvmCell g_problem_code ; // The code of EulerUser contracts TvmCell g_user_code ; /// @dev The user must only provide the codes of EulerProblem and /// EulerUser contracts constructor( TvmCell problem_code, TvmCell user_code ) public { require( msg.pubkey() == tvm.pubkey(), EXN_AUTH_FAILED ); require( address(this).balance >= 2 ton, EXN_NOT_ENOUGH_VALUE ); tvm.accept(); g_owner = msg.pubkey() ; g_problem_code = problem_code ; g_user_code = user_code ; } /// @dev Deploys a EulerProblem contract for a new Euler problem. Only the /// owner of the EulerRoot can call this function. /// @param problem The number of the problem /// @param verifkey The Groth16 verification key of the problem /// @param zip_provkey A compressed version of the Groth16 proving key /// of the problem, used to create a submission locally /// @param nonce The nonce that the user must provide with his submission /// @param title The title of the problem /// @param description The description of the problem /// @param url The link to the problem official description function new_problem( uint32 problem, bytes verifkey, bytes zip_provkey, string nonce, string title, string description, string url) public view returns ( address addr ) { require( g_owner == msg.pubkey(), EXN_AUTH_FAILED ); require( address(this).balance > 1 ton, EXN_NOT_ENOUGH_VALUE ); tvm.accept() ; addr = new EulerProblem { value: 1 ton, pubkey: tvm.pubkey() , code: g_problem_code , varInit: { s_problem: problem , s_root_contract: this } }( verifkey, zip_provkey, nonce, title, description, url ); } /// @dev This function deploys a EulerUser contract associated with a /// given public key. Anybody can call this function from a multisig. /// @param pubkey: The user pubkey function new_user( uint256 pubkey ) public view returns ( address addr ) { require( msg.value >= 1 ton, EXN_AUTH_FAILED ); addr = new EulerUser { value: msg.value - 0.1 ton, pubkey: pubkey , code: g_user_code , varInit: { s_root_contract: this } }() ; } /// @dev Returns the address of the EulerProblem contract associated /// with a given problem number. The contract exists only if /// 'new_problem' has been called before. /// @param problem : the number of the problem function problem_address( uint32 problem ) public view returns ( address addr ) { TvmCell stateInit = tvm.buildStateInit({ contr: EulerProblem , pubkey: tvm.pubkey() , code: g_problem_code , varInit: { s_problem: problem , s_root_contract: this } }); addr = address(tvm.hash(stateInit)); } /// @dev returns the address of the EulerUser contract associated /// with a given pubkey. The contract only exists if 'new_user' has /// been called before. function user_address( uint256 pubkey ) public view returns ( address addr ) { TvmCell stateInit = tvm.buildStateInit({ contr: EulerUser , pubkey: pubkey , code: g_user_code , varInit: { s_root_contract: this } }); addr = address(tvm.hash(stateInit)); } /// @dev submits a solution to a given problem, using a proof /// generated by euler-client C++ program, associated with the /// given pubkey. The proof will fail if another pubkey is /// provided. /// @param problem: number of the problem /// @param proof: the 'proof.bin' generated by euler-client /// @param pubkey: the pubkey of the user, as used when generating /// 'proof.bin' function submit( uint32 problem, bytes proof, uint256 pubkey) public view override { address addr = problem_address( problem ); EulerProblem( addr ).submit { value:0, flag: 64} ( problem, proof, pubkey ); } /// @dev updates the Blueprint circuit associated with a given problem /// @param problem: the number of the problem /// @param verifkey: the new verification key of the circuit /// @param zip_provkey: the new proving key of the circuit to be used to /// generate submission proofs /// @param nonce: the nonce to be used to generate submission proofs function update_circuit( uint32 problem, bytes verifkey, bytes zip_provkey, string nonce ) public view { require( g_owner == msg.pubkey(), EXN_AUTH_FAILED ); tvm.accept(); address addr = problem_address( problem ); EulerProblem( addr ).update_circuit { value:0.2 ton } ( verifkey, zip_provkey, nonce ); } /// @dev Updates the description of a problem. Only called by the owner of /// the EulerRoot contract. /// @param problem: the number of the problem /// @param title: the new title of the problem or empty string /// @param description: the new description of the problem or empty string /// @param url: the new url of the problem or empty string function update_problem( uint32 problem, string title, string description, string url ) public view { require( g_owner == msg.pubkey(), EXN_AUTH_FAILED ); tvm.accept(); address addr = problem_address( problem ); EulerProblem( addr ).update_problem { value:0.2 ton } ( title, description, url ); } /// @dev This function is called by a EulerProblem when a user /// successfully submitted a solution. The function verifies that /// the sender is indeed an EulerProblem contract as expected. The /// function emits en event and calls the EulerUser contract to /// record the information /// @param problem: the number of the problem /// @param pubkey: the user pubkey who successfully solved the problem function has_solved( uint32 problem, uint256 pubkey ) public override { address addr = problem_address( problem ) ; require( addr == msg.sender, EXN_AUTH_FAILED ); emit ProblemSolved( problem, pubkey ); addr = user_address( pubkey ); EulerUser( addr ).has_solved{ value:0, flag: 64 }( problem ); } /// @dev This get-method function is used to recover information on /// this contract function get() public view returns ( uint256 owner, uint256 problem_code_hash, uint256 user_code_hash ) { owner = g_owner ; problem_code_hash = tvm.hash ( g_problem_code ); user_code_hash = tvm.hash ( g_user_code ); } /// @dev This internal function is used to change the owner of the /// contract using the pincode-client smart contract (described in /// 03-pincode section) function recover_pubkey ( uint256 oldkey, uint256 newkey) internal override { if( oldkey == g_owner ){ g_owner = newkey; } } }
This internal function is used to change the owner of the contract using the pincode-client smart contract (described in 03-pincode section)
function recover_pubkey ( uint256 oldkey, uint256 newkey) internal override { if( oldkey == g_owner ){ g_owner = newkey; } }
13,107,321
./full_match/80001/0xAf78b5Ba6AC07eA31D95cF00b9a37A6b32624480/sources/contracts/protocol/config/MarketConfig.sol
Returns sum of all fees (1 = 0.01%)/
function feesSum() external override view returns(uint256){ return burnFee + foundationFee + marketCreatorFee + verificationFee; }
5,626,845
/** *Submitted for verification at Etherscan.io on 2020-05-29 */ pragma solidity ^0.5.0; 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); } 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); } contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is Context, ERC20{ using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } 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; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } 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; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } 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; } 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; } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); totalSupply_ = totalSupply_.add(amount); balances[account] = balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); balances[account] = balances[account].sub(amount, "ERC20: burn amount exceeds balance"); totalSupply_ = totalSupply_.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address _spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowed[owner][_spender] = amount; emit Approval(owner, _spender, amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, allowed[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } contract Pausable is Ownable { event Pause(); event Unpause(); event NotPausable(); bool public paused = false; bool public canPause = true; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused || msg.sender == owner); _; } /** * @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 { require(canPause == true); paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { require(paused == true); paused = false; emit Unpause(); } /** * @dev Prevent the token from ever being paused again **/ function notPausable() onlyOwner public{ paused = false; canPause = false; emit NotPausable(); } } contract Mintable is BasicToken, 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); 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; } } contract ERC20Burnable is Context, BasicToken { function burn(uint256 amount) public { _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } contract ERC20Detailed is ERC20 { 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 name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } contract PausableToken is BasicToken, ERC20Detailed, Pausable, ERC20Burnable, Mintable { string public constant NAME = "beautyon"; string public constant SYMBOL = "bto"; uint256 public constant DECIMALS = 8; uint256 public constant INITIAL_SUPPLY = 2000000000 * 10**8; /** * @dev Transfer tokens when not paused **/ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } /** * @dev transferFrom function to tansfer tokens when token is not paused **/ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev approve spender when not paused **/ function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev increaseApproval of spender when not paused **/ function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * @dev decreaseApproval of spender when not paused **/ function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } /** * Pausable Token Constructor * @dev Create and issue tokens to msg.sender. */ /* constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } */ constructor () public ERC20Detailed("beautyon", "bto", 8) { _mint(0x068aeb16e5Bb1F1743Fe515D0FC77C5e81d3C8D2, 2000000000 * (10 ** uint256(decimals()))); } }
Transfer tokens when not paused/
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); }
168,743
pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title 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; } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal 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(_value <= balances[msg.sender]); require(_to != address(0)); 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 Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); 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) { 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 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 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; } } contract IdaToken is Ownable, RBAC, StandardToken { using AddressUtils for address; using SafeMath for uint256; string public name = "IDA"; string public symbol = "IDA"; uint8 public decimals = 18; // 初始发行量 100 亿 uint256 public constant INITIAL_SUPPLY = 10000000000; // 基石轮额度 3.96 亿 uint256 public constant FOOTSTONE_ROUND_AMOUNT = 396000000; // 私募额度 12 亿 uint256 public constant PRIVATE_SALE_AMOUNT = 1200000000; // 2019/05/01 之前的 Owner 锁仓额度 50 亿 uint256 public constant OWNER_LOCKED_IN_COMMON = 5000000000; // 通用额度 72.04 亿 (IDA 基金会、研发、生态建设、社区建设、运营) uint256 public constant COMMON_PURPOSE_AMOUNT = 7204000000; // 团队预留额度1 1.2 亿 uint256 public constant TEAM_RESERVED_AMOUNT1 = 120000000; // 团队预留额度2 3.6 亿 uint256 public constant TEAM_RESERVED_AMOUNT2 = 360000000; // 团队预留额度3 3.6 亿 uint256 public constant TEAM_RESERVED_AMOUNT3 = 360000000; // 团队预留额度4 3.6 亿 uint256 public constant TEAM_RESERVED_AMOUNT4 = 360000000; // 私募中的 Ether 兑换比率,1 Ether = 10000 IDA uint256 public constant EXCHANGE_RATE_IN_PRIVATE_SALE = 10000; // 2018/10/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20181001000001 = 1538352001; // 2018/10/02 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20181002000001 = 1538438401; // 2018/11/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20181101000001 = 1541030401; // 2019/02/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20190201000001 = 1548979201; // 2019/05/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20190501000001 = 1556668801; // 2019/08/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20190801000001 = 1564617601; // 2019/11/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20191101000001 = 1572566401; // 2020/11/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20201101000001 = 1604188801; // 2021/11/01 00:00:01 的时间戳常数 uint256 public constant TIMESTAMP_OF_20211101000001 = 1635724801; // Role constant of Partner Whitelist string public constant ROLE_PARTNERWHITELIST = "partnerWhitelist"; // Role constant of Privatesale Whitelist string public constant ROLE_PRIVATESALEWHITELIST = "privateSaleWhitelist"; // 由 Owner 分发的总数额 uint256 public totalOwnerReleased; // 所有 partner 的已分发额总数 uint256 public totalPartnersReleased; // 所有私募代理人的已分发数额总数 uint256 public totalPrivateSalesReleased; // 通用额度的已分发数额总数 uint256 public totalCommonReleased; // 团队保留额度的已分发数额总数1 uint256 public totalTeamReleased1; // 团队保留额度的已分发数额总数2 uint256 public totalTeamReleased2; // 团队保留额度的已分发数额总数3 uint256 public totalTeamReleased3; // 团队保留额度的已分发数额总数4 uint256 public totalTeamReleased4; // Partner 地址数组 address[] private partners; // Partner 地址在数组中索引 mapping (address => uint256) private partnersIndex; // 私募代理人地址数组 address[] private privateSaleAgents; // 私募代理人地址在数组中的索引 mapping (address => uint256) private privateSaleAgentsIndex; // Partner 限额映射 mapping (address => uint256) private partnersAmountLimit; // Partner 实际已转账额度映射 mapping (address => uint256) private partnersWithdrawed; // 私募代理人实际转出(售出)的 token 数量映射 mapping (address => uint256) private privateSalesReleased; // Owner 的钱包地址 address ownerWallet; // Log 特定的转账函数操作 event TransferLog(address from, address to, bytes32 functionName, uint256 value); /** * @dev 构造函数时需传入 Owner 指定的钱包地址 * @param _ownerWallet Owner 的钱包地址 */ constructor(address _ownerWallet) public { ownerWallet = _ownerWallet; totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals)); balances[msg.sender] = totalSupply_; } /** * @dev 变更 Owner 的钱包地址 * @param _ownerWallet Owner 的钱包地址 */ function changeOwnerWallet(address _ownerWallet) public onlyOwner { ownerWallet = _ownerWallet; } /** * @dev 添加 partner 地址到白名单并设置其限额 * @param _addr Partner 地址 * @param _amount Partner 的持有限额 */ function addAddressToPartnerWhiteList(address _addr, uint256 _amount) public onlyOwner { // 仅允许在 2018/11/01 00:00:01 之前调用 require(block.timestamp < TIMESTAMP_OF_20181101000001); // 如 _addr 不在白名单内,则执行添加处理 if (!hasRole(_addr, ROLE_PARTNERWHITELIST)) { addRole(_addr, ROLE_PARTNERWHITELIST); // 把给定地址加入 partner 数组 partnersIndex[_addr] = partners.length; partners.push(_addr); } // Owner 可以多次调用此函数以达到修改 partner 授权上限的效果 partnersAmountLimit[_addr] = _amount; } /** * @dev 将 partner 地址从白名单移除 * @param _addr Partner 地址 */ function removeAddressFromPartnerWhiteList(address _addr) public onlyOwner { // 仅允许在 2018/11/01 00:00:01 之前调用 require(block.timestamp < TIMESTAMP_OF_20181101000001); // 仅允许 _addr 已在白名单内时使用 require(hasRole(_addr, ROLE_PARTNERWHITELIST)); removeRole(_addr, ROLE_PARTNERWHITELIST); partnersAmountLimit[_addr] = 0; // 把给定地址从 partner 数组中删除 uint256 partnerIndex = partnersIndex[_addr]; uint256 lastPartnerIndex = partners.length.sub(1); address lastPartner = partners[lastPartnerIndex]; partners[partnerIndex] = lastPartner; delete partners[lastPartnerIndex]; partners.length--; partnersIndex[_addr] = 0; partnersIndex[lastPartner] = partnerIndex; } /** * @dev 添加私募代理人地址到白名单并设置其限额 * @param _addr 私募代理人地址 * @param _amount 私募代理人的转账限额 */ function addAddressToPrivateWhiteList(address _addr, uint256 _amount) public onlyOwner { // 仅允许在 2018/10/02 00:00:01 之前调用 require(block.timestamp < TIMESTAMP_OF_20181002000001); // 检查 _addr 是否已在白名单内以保证 approve 函数仅会被调用一次; // 后续如还需要更改授权额度, // 请直接使用安全的 increaseApproval 和 decreaseApproval 函数 require(!hasRole(_addr, ROLE_PRIVATESALEWHITELIST)); addRole(_addr, ROLE_PRIVATESALEWHITELIST); approve(_addr, _amount); // 把给定地址加入私募代理人数组 privateSaleAgentsIndex[_addr] = privateSaleAgents.length; privateSaleAgents.push(_addr); } /** * @dev 将私募代理人地址从白名单移除 * @param _addr 私募代理人地址 */ function removeAddressFromPrivateWhiteList(address _addr) public onlyOwner { // 仅允许在 2018/10/02 00:00:01 之前调用 require(block.timestamp < TIMESTAMP_OF_20181002000001); // 仅允许 _addr 已在白名单内时使用 require(hasRole(_addr, ROLE_PRIVATESALEWHITELIST)); removeRole(_addr, ROLE_PRIVATESALEWHITELIST); approve(_addr, 0); // 把给定地址从私募代理人数组中删除 uint256 agentIndex = privateSaleAgentsIndex[_addr]; uint256 lastAgentIndex = privateSaleAgents.length.sub(1); address lastAgent = privateSaleAgents[lastAgentIndex]; privateSaleAgents[agentIndex] = lastAgent; delete privateSaleAgents[lastAgentIndex]; privateSaleAgents.length--; privateSaleAgentsIndex[_addr] = 0; privateSaleAgentsIndex[lastAgent] = agentIndex; } /** * @dev 允许接受转账的 fallback 函数 */ function() external payable { privateSale(msg.sender); } /** * @dev 私募处理 * @param _beneficiary 收取 token 地址 */ function privateSale(address _beneficiary) public payable onlyRole(ROLE_PRIVATESALEWHITELIST) { // 仅允许 EOA 购买 require(msg.sender == tx.origin); require(!msg.sender.isContract()); // 仅允许在 2018/10/02 00:00:01 之前购买 require(block.timestamp < TIMESTAMP_OF_20181002000001); uint256 purchaseValue = msg.value.mul(EXCHANGE_RATE_IN_PRIVATE_SALE); transferFrom(owner, _beneficiary, purchaseValue); } /** * @dev 人工私募处理 * @param _addr 收取 token 地址 * @param _amount 转账 token 数量 */ function withdrawPrivateCoinByMan(address _addr, uint256 _amount) public onlyRole(ROLE_PRIVATESALEWHITELIST) { // 仅允许在 2018/10/02 00:00:01 之前购买 require(block.timestamp < TIMESTAMP_OF_20181002000001); // 仅允许 EOA 获得转账 require(!_addr.isContract()); transferFrom(owner, _addr, _amount); } /** * @dev 私募余额提取 * @param _amount 提取 token 数量 */ function withdrawRemainPrivateCoin(uint256 _amount) public onlyOwner { // 仅允许在 2018/10/01 00:00:01 之后提取 require(block.timestamp >= TIMESTAMP_OF_20181001000001); require(transfer(ownerWallet, _amount)); emit TransferLog(owner, ownerWallet, bytes32("withdrawRemainPrivateCoin"), _amount); } /** * @dev 私募转账处理(从 Owner 持有的余额中转出) * @param _to 转入地址 * @param _amount 转账数量 */ function _privateSaleTransferFromOwner(address _to, uint256 _amount) private returns (bool) { uint256 newTotalPrivateSaleAmount = totalPrivateSalesReleased.add(_amount); // 检查私募转账总额是否超限 require(newTotalPrivateSaleAmount <= PRIVATE_SALE_AMOUNT.mul(10 ** uint256(decimals))); bool result = super.transferFrom(owner, _to, _amount); privateSalesReleased[msg.sender] = privateSalesReleased[msg.sender].add(_amount); totalPrivateSalesReleased = newTotalPrivateSaleAmount; return result; } /** * @dev 合约余额提取 */ function withdrawFunds() public onlyOwner { ownerWallet.transfer(address(this).balance); } /** * @dev 获取所有 Partner 地址 * @return 所有 Partner 地址 */ function getPartnerAddresses() public onlyOwner view returns (address[]) { return partners; } /** * @dev 获取所有私募代理人地址 * @return 所有私募代理人地址 */ function getPrivateSaleAgentAddresses() public onlyOwner view returns (address[]) { return privateSaleAgents; } /** * @dev 获得私募代理人地址已转出(售出)的 token 数量 * @param _addr 私募代理人地址 * @return 私募代理人地址的已转出的 token 数量 */ function privateSaleReleased(address _addr) public view returns (uint256) { return privateSalesReleased[_addr]; } /** * @dev 获得 Partner 地址的提取限额 * @param _addr Partner 的地址 * @return Partner 地址的提取限额 */ function partnerAmountLimit(address _addr) public view returns (uint256) { return partnersAmountLimit[_addr]; } /** * @dev 获得 Partner 地址的已提取 token 数量 * @param _addr Partner 的地址 * @return Partner 地址的已提取 token 数量 */ function partnerWithdrawed(address _addr) public view returns (uint256) { return partnersWithdrawed[_addr]; } /** * @dev 给 Partner 地址分发 token * @param _addr Partner 的地址 * @param _amount 分发的 token 数量 */ function withdrawToPartner(address _addr, uint256 _amount) public onlyOwner { require(hasRole(_addr, ROLE_PARTNERWHITELIST)); // 仅允许在 2018/11/01 00:00:01 之前分发 require(block.timestamp < TIMESTAMP_OF_20181101000001); uint256 newTotalReleased = totalPartnersReleased.add(_amount); require(newTotalReleased <= FOOTSTONE_ROUND_AMOUNT.mul(10 ** uint256(decimals))); uint256 newPartnerAmount = balanceOf(_addr).add(_amount); require(newPartnerAmount <= partnersAmountLimit[_addr]); totalPartnersReleased = newTotalReleased; transfer(_addr, _amount); emit TransferLog(owner, _addr, bytes32("withdrawToPartner"), _amount); } /** * @dev 计算 Partner 地址的可提取 token 数量,返回其与 _value 之间较小的那个值 * @param _addr Partner 的地址 * @param _value 想要提取的 token 数量 * @return Partner 地址当前可提取的 token 数量, * 如果 _value 较小,则返回 _value 的数值 */ function _permittedPartnerTranferValue(address _addr, uint256 _value) private view returns (uint256) { uint256 limit = balanceOf(_addr); uint256 withdrawed = partnersWithdrawed[_addr]; uint256 total = withdrawed.add(limit); uint256 time = block.timestamp; require(limit > 0); if (time >= TIMESTAMP_OF_20191101000001) { // 2019/11/01 00:00:01 之后可提取 100% limit = total; } else if (time >= TIMESTAMP_OF_20190801000001) { // 2019/08/01 00:00:01 之后最多提取 75% limit = total.mul(75).div(100); } else if (time >= TIMESTAMP_OF_20190501000001) { // 2019/05/01 00:00:01 之后最多提取 50% limit = total.div(2); } else if (time >= TIMESTAMP_OF_20190201000001) { // 2019/02/01 00:00:01 之后最多提取 25% limit = total.mul(25).div(100); } else { // 2019/02/01 00:00:01 之前不可提取 limit = 0; } if (withdrawed >= limit) { limit = 0; } else { limit = limit.sub(withdrawed); } if (_value < limit) { limit = _value; } return limit; } /** * @dev 重写基础合约的 transferFrom 函数 */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { bool result; address sender = msg.sender; if (_from == owner) { if (hasRole(sender, ROLE_PRIVATESALEWHITELIST)) { // 仅允许在 2018/10/02 00:00:01 之前购买 require(block.timestamp < TIMESTAMP_OF_20181002000001); result = _privateSaleTransferFromOwner(_to, _value); } else { revert(); } } else { result = super.transferFrom(_from, _to, _value); } return result; } /** * @dev 通用额度提取 * @param _amount 提取 token 数量 */ function withdrawCommonCoin(uint256 _amount) public onlyOwner { // 仅允许在 2018/11/01 00:00:01 之后提取 require(block.timestamp >= TIMESTAMP_OF_20181101000001); require(transfer(ownerWallet, _amount)); emit TransferLog(owner, ownerWallet, bytes32("withdrawCommonCoin"), _amount); totalCommonReleased = totalCommonReleased.add(_amount); } /** * @dev 团队预留额度1提取 * @param _amount 提取 token 数量 */ function withdrawToTeamStep1(uint256 _amount) public onlyOwner { // 仅允许在 2019/02/01 00:00:01 之后提取 require(block.timestamp >= TIMESTAMP_OF_20190201000001); require(transfer(ownerWallet, _amount)); emit TransferLog(owner, ownerWallet, bytes32("withdrawToTeamStep1"), _amount); totalTeamReleased1 = totalTeamReleased1.add(_amount); } /** * @dev 团队预留额度2提取 * @param _amount 提取 token 数量 */ function withdrawToTeamStep2(uint256 _amount) public onlyOwner { // 仅允许在 2019/11/01 00:00:01 之后提取 require(block.timestamp >= TIMESTAMP_OF_20191101000001); require(transfer(ownerWallet, _amount)); emit TransferLog(owner, ownerWallet, bytes32("withdrawToTeamStep2"), _amount); totalTeamReleased2 = totalTeamReleased2.add(_amount); } /** * @dev 团队预留额度3提取 * @param _amount 提取 token 数量 */ function withdrawToTeamStep3(uint256 _amount) public onlyOwner { // 仅允许在 2020/11/01 00:00:01 之后提取 require(block.timestamp >= TIMESTAMP_OF_20201101000001); require(transfer(ownerWallet, _amount)); emit TransferLog(owner, ownerWallet, bytes32("withdrawToTeamStep3"), _amount); totalTeamReleased3 = totalTeamReleased3.add(_amount); } /** * @dev 团队预留额度4提取 * @param _amount 提取 token 数量 */ function withdrawToTeamStep4(uint256 _amount) public onlyOwner { // 仅允许在 2021/11/01 00:00:01 之后提取 require(block.timestamp >= TIMESTAMP_OF_20211101000001); require(transfer(ownerWallet, _amount)); emit TransferLog(owner, ownerWallet, bytes32("withdrawToTeamStep4"), _amount); totalTeamReleased4 = totalTeamReleased4.add(_amount); } /** * @dev 重写基础合约的 transfer 函数 */ function transfer(address _to, uint256 _value) public returns (bool) { bool result; uint256 limit; if (msg.sender == owner) { limit = _ownerReleaseLimit(); uint256 newTotalOwnerReleased = totalOwnerReleased.add(_value); require(newTotalOwnerReleased <= limit); result = super.transfer(_to, _value); totalOwnerReleased = newTotalOwnerReleased; } else if (hasRole(msg.sender, ROLE_PARTNERWHITELIST)) { limit = _permittedPartnerTranferValue(msg.sender, _value); if (limit > 0) { result = super.transfer(_to, limit); partnersWithdrawed[msg.sender] = partnersWithdrawed[msg.sender].add(limit); } else { revert(); } } else { result = super.transfer(_to, _value); } return result; } /** * @dev 计算 Owner 的转账额度 * @return Owner 的当前转账额度 */ function _ownerReleaseLimit() private view returns (uint256) { uint256 time = block.timestamp; uint256 limit; uint256 amount; // 基石轮额度作为默认限额 limit = FOOTSTONE_ROUND_AMOUNT.mul(10 ** uint256(decimals)); if (time >= TIMESTAMP_OF_20181001000001) { // 2018/10/1 之后,最大限额需要增加私募剩余额度 amount = PRIVATE_SALE_AMOUNT.mul(10 ** uint256(decimals)); if (totalPrivateSalesReleased < amount) { limit = limit.add(amount).sub(totalPrivateSalesReleased); } } if (time >= TIMESTAMP_OF_20181101000001) { // 2018/11/1 之后,最大限额需要增加通用提取额度中减去锁仓额度以外的额度 limit = limit.add(COMMON_PURPOSE_AMOUNT.sub(OWNER_LOCKED_IN_COMMON).mul(10 ** uint256(decimals))); } if (time >= TIMESTAMP_OF_20190201000001) { // 2019/2/1 之后,最大限额需要增加团队预留额度1 limit = limit.add(TEAM_RESERVED_AMOUNT1.mul(10 ** uint256(decimals))); } if (time >= TIMESTAMP_OF_20190501000001) { // 2019/5/1 之后,最大限额需要增加通用额度中的锁仓额度 limit = limit.add(OWNER_LOCKED_IN_COMMON.mul(10 ** uint256(decimals))); } if (time >= TIMESTAMP_OF_20191101000001) { // 2019/11/1 之后,最大限额需要增加团队预留额度2 limit = limit.add(TEAM_RESERVED_AMOUNT2.mul(10 ** uint256(decimals))); } if (time >= TIMESTAMP_OF_20201101000001) { // 2020/11/1 之后,最大限额需要增加团队预留额度3 limit = limit.add(TEAM_RESERVED_AMOUNT3.mul(10 ** uint256(decimals))); } if (time >= TIMESTAMP_OF_20211101000001) { // 2021/11/1 之后,最大限额需要增加团队预留额度4 limit = limit.add(TEAM_RESERVED_AMOUNT4.mul(10 ** uint256(decimals))); } return limit; } }
获取所有 Partner 地址 return 所有 Partner 地址/
function getPartnerAddresses() public onlyOwner view returns (address[]) { return partners; }
5,514,005
// File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.8; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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: contracts/access/Roles.sol /** * @title Roles * @notice copied from openzeppelin-solidity * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts/access/WhitelistAdminRole.sol /** * @title WhitelistAdminRole * @notice copied from openzeppelin-solidity * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: contracts/access/WhitelistedRole.sol /** * @title WhitelistedRole * @notice copied from openzeppelin-solidity * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is Context, WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(_msgSender()); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: contracts/oracle/ICADConversionOracle.sol /** * @title ICADRateOracle * @notice provides interface for converting USD stable coins to CAD */ interface ICADConversionOracle { /** * @notice convert USD amount to CAD amount * @param amount amount of USD in 18 decimal places * @return amount of CAD in 18 decimal places */ function usdToCad(uint256 amount) external view returns (uint256); /** * @notice convert Dai amount to CAD amount * @param amount amount of dai in 18 decimal places * @return amount of CAD in 18 decimal places */ function daiToCad(uint256 amount) external view returns (uint256); /** * @notice convert USDC amount to CAD amount * @param amount amount of USDC in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdcToCad(uint256 amount) external view returns (uint256); /** * @notice convert USDT amount to CAD amount * @param amount amount of USDT in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdtToCad(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to USD amount * @param amount amount of CAD in 18 decimal places * @return amount of USD in 18 decimal places */ function cadToUsd(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to Dai amount * @param amount amount of CAD in 18 decimal places * @return amount of Dai in 18 decimal places */ function cadToDai(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to USDC amount * @param amount amount of CAD in 18 decimal places * @return amount of USDC in 6 decimal places */ function cadToUsdc(uint256 amount) external view returns (uint256); /** * @notice convert CAD amount to USDT amount * @param amount amount of CAD in 18 decimal places * @return amount of USDT in 6 decimal places */ function cadToUsdt(uint256 amount) external view returns (uint256); } // File: contracts/oracle/ManagedCADChainlinkRateOracle.sol /** * @title ManagedCADChainlinkRateOracle * @notice Provides a USD/CAD rate source managed by admin, and Chainlink powered DAI/USDC/USDT conversion rates. * USDC is treated as always 1 USD, and used as anchor to calculate Dai and USDT rates */ contract ManagedCADChainlinkRateOracle is ICADConversionOracle, WhitelistedRole { using SafeMath for uint256; event ManagedRateUpdated(uint256 value, uint256 timestamp); // exchange rate stored as an integer uint256 public _USDToCADRate; // specifies how many decimal places have been converted into integer uint256 public _granularity; // specifies the time the exchange was last updated uint256 public _timestamp; // Chainlink price feed for Dai/Eth pair AggregatorV3Interface public daiEthPriceFeed; // Chainlink price feed for USDC/Eth pair AggregatorV3Interface public usdcEthPriceFeed; // Chainlink price feed for USDT/Eth pair AggregatorV3Interface public usdtEthPriceFeed; constructor( uint256 value, uint256 granularity, address daiEthAggregatorAddress, address usdcEthAggregatorAddress, address usdtEthAggregatorAddress ) public { _USDToCADRate = value; _granularity = granularity; _timestamp = block.timestamp; daiEthPriceFeed = AggregatorV3Interface(daiEthAggregatorAddress); usdcEthPriceFeed = AggregatorV3Interface(usdcEthAggregatorAddress); usdtEthPriceFeed = AggregatorV3Interface(usdtEthAggregatorAddress); _addWhitelisted(msg.sender); } /** * @notice admin can update the exchange rate * @param value the new exchange rate * @param granularity number of decimal places the exchange value is accurate to * @return true if success */ function updateManagedRate(uint256 value, uint256 granularity) external onlyWhitelisted returns (bool) { require(value > 0, "Exchange rate cannot be zero"); require(granularity > 0, "Granularity cannot be zero"); _USDToCADRate = value; _granularity = granularity; _timestamp = block.timestamp; emit ManagedRateUpdated(value, granularity); return true; } /** * @notice return the current managed values * @return latest USD to CAD exchange rate, granularity, and timestamp */ function getManagedRate() external view returns (uint256, uint256, uint256) { return (_USDToCADRate, _granularity, _timestamp); } /** * @notice convert USD amount to CAD amount * @param amount amount of USD in 18 decimal places * @return amount of CAD in 18 decimal places */ function usdToCad(uint256 amount) public view virtual override returns (uint256) { return amount.mul(_USDToCADRate).div(10 ** _granularity); } /** * @notice convert Dai amount to CAD amount * @param amount amount of dai in 18 decimal places * @return amount of CAD in 18 decimal places */ function daiToCad(uint256 amount) external view virtual override returns (uint256) { (, int256 daiEthPrice, , uint256 daiEthTimeStamp,) = daiEthPriceFeed.latestRoundData(); require(daiEthTimeStamp > 0, "Dai Chainlink Oracle data temporarily incomplete"); require(daiEthPrice > 0, "Invalid Chainlink Oracle Dai price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(_USDToCADRate).mul(uint256(daiEthPrice)).div(uint256(usdcEthPrice)).div(10 ** _granularity); } /** * @notice convert USDC amount to CAD amount * @param amount amount of USDC in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdcToCad(uint256 amount) external view virtual override returns (uint256) { // USDT has 6 decimals return usdToCad(amount.mul(1e12)); } /** * @notice convert USDT amount to CAD amount * @param amount amount of USDT in 6 decimal places * @return amount of CAD in 18 decimal places */ function usdtToCad(uint256 amount) external view virtual override returns (uint256) { (, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData(); require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete"); require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); // USDT has 6 decimals return amount.mul(1e12).mul(_USDToCADRate).mul(uint256(usdtEthPrice)).div(uint256(usdcEthPrice)).div(10 ** _granularity); } /** * @notice convert CAD amount to USD amount * @param amount amount of CAD in 18 decimal places * @return amount of USD in 18 decimal places */ function cadToUsd(uint256 amount) public view virtual override returns (uint256) { return amount.mul(10 ** _granularity).div(_USDToCADRate); } /** * @notice convert CAD amount to Dai amount * @param amount amount of CAD in 18 decimal places * @return amount of Dai in 18 decimal places */ function cadToDai(uint256 amount) external view virtual override returns (uint256) { (, int256 daiEthPrice, , uint256 daiEthTimeStamp,) = daiEthPriceFeed.latestRoundData(); require(daiEthTimeStamp > 0, "Dai Chainlink Oracle data temporarily incomplete"); require(daiEthPrice > 0, "Invalid Chainlink Oracle Dai price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(daiEthPrice)).div(_USDToCADRate); } /** * @notice convert CAD amount to USDC amount * @param amount amount of CAD in 18 decimal places * @return amount of USDC in 6 decimal places */ function cadToUsdc(uint256 amount) external view virtual override returns (uint256) { return cadToUsd(amount).div(1e12); } /** * @notice convert CAD amount to USDT amount * @param amount amount of CAD in 18 decimal places * @return amount of USDT in 6 decimal places */ function cadToUsdt(uint256 amount) external view virtual override returns (uint256) { (, int256 usdtEthPrice, , uint256 usdtEthTimeStamp,) = usdtEthPriceFeed.latestRoundData(); require(usdtEthTimeStamp > 0, "USDT Chainlink Oracle data temporarily incomplete"); require(usdtEthPrice > 0, "Invalid Chainlink Oracle USDT price"); (, int256 usdcEthPrice, , uint256 usdcEthTimeStamp,) = usdcEthPriceFeed.latestRoundData(); require(usdcEthTimeStamp > 0, "USDC conversion Chainlink Oracle data temporarily incomplete"); require(usdcEthPrice > 0, "Invalid Chainlink Oracle USDC conversion price"); return amount.mul(10 ** _granularity).mul(uint256(usdcEthPrice)).div(uint256(usdtEthPrice)).div(_USDToCADRate).div(1e12); } }
getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
295,899
pragma solidity ^0.4.24; import '../../common/AppDAO.sol'; /** * @title CrowdSale interface to get wallet address */ interface CrowdSaleI { function Wallet() external returns (address); } /** * @title Application Token based on ERC20, AppDAO, AppDD */ contract AppToken is AppDAO { bytes32 public version = "ERC20 2.0.0"; uint public initialSupply = 100 * 10**3; // default 100 thousand tokens uint public decimals = 8; string public name; string public symbol; address public Wallet; /** Name and symbol were updated. */ event UpdatedTokenInformation(string _name, string _symbol); /** Period were updated. */ event UpdatedPeriod(uint _period); constructor(string _name, string _symbol, address _CrowdSale, address _PMFund, address _dev) public { name = _name; symbol = _symbol; totalSupply_ = initialSupply*10**decimals; // creating initial tokens balances[_CrowdSale] = totalSupply_; emit Transfer(0x0, _CrowdSale, balances[_CrowdSale]); // send 5% - to DAO PlayMarket 2.0 Foundation uint value = safePerc(totalSupply_,500); balances[_CrowdSale] = safeSub(balances[_CrowdSale], value); balances[_PMFund] = value; emit Transfer(_CrowdSale, _PMFund, balances[_PMFund]); Wallet = CrowdSaleI(_CrowdSale).Wallet(); require(Wallet != address(0)); // send 55% - to developer for the organization AirDrop/Bounty etc. value = safePerc(totalSupply_,5500); balances[_CrowdSale] = safeSub(balances[_CrowdSale], value); balances[Wallet] = value; emit Transfer(_CrowdSale, Wallet, balances[Wallet]); ChangeOverPeriod[_CrowdSale][1] = int256(balances[_CrowdSale]); owners.push(_CrowdSale); ChangeOverPeriod[_PMFund][1] = int256(balances[_PMFund]); owners.push(_PMFund); ChangeOverPeriod[Wallet][1] = int256(balances[Wallet]); owners.push(Wallet); // _minimumQuorum = safePerc(totalSupply_, 5000) // _requisiteMajority = safePerc(totalSupply_, 2500) // _debatingPeriodDuration = 60 minutes changeVotingRules(safePerc(totalSupply_, 5000), 60, safePerc(totalSupply_, 2500)); // change owner owner = address(_CrowdSale); } /** * Owner can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function setTokenInformation(string _name, string _symbol) public onlyOwner { name = _name; symbol = _symbol; emit UpdatedTokenInformation(_name, _symbol); } /** * Owner can change start one time */ function setStart(uint _start) external onlyOwner { require(start == 0); start = _start; } /** * Owner can change period * */ function setPeriod(uint _period) public onlyOwner { period = _period; emit UpdatedPeriod(_period); owner = address(this); } }
CrowdSale interface to get wallet address/
interface CrowdSaleI { function Wallet() external returns (address); }
12,724,547
./full_match/1/0xebbF9d920Ca38Ec90181d40aA7E623b5A2807887/sources/contracts/UniswapV2FlashCalculate.sol
计算利润 returns: @maxAmountBuy 最大购买额度 @finallyAmountOutOfBot 最终可获得的Token数量 @finallyAmountOutOfUser 对手最终可获得Token数量 @profit 利润 uint256 ETHBalance = WETH.balanceOf(address(this)); 判断Pair里面的 Token0 是否为需要购买的Token;主要用来区别 reserves 位置 将合约的WETH余额分成100等份,然后按照各个梯度进行模拟购买;从而判断最大购买值 uint256 step = uint256(1000e18 / 1000); 如果对方是复合路径,则需要重新计算amountInOfUser;新的amountInOfUser为复合路径的倒数第二个值; 处理机器人购买路径为复合路径的情况下计算有效利润。
function V2CalculateMaxAmount(uint256 amountInOfUser, uint256 amountOutMin, address[] memory userPath, address[] memory minePath) external view returns ( uint256 maxAmountBuy, uint256 finallyAmountOutOfBot, uint256 finallyAmountOutOfUser, int256 profit, uint256 step ) { require(userPath.length > 1, "Opponent path length error"); (address pair,bool isToken1, ,) = V2GetPairToken(userPath); step = uint256(IERC20(minePath[0]).balanceOf(bundleExecutorAddress) / exact); require(step > 0, "Path Insufficient balance"); if (userPath.length > 2) { uint256[] memory opponentAmounts = V2GetAmountsOutByStepPath(amountInOfUser, userPath); amountInOfUser = opponentAmounts[opponentAmounts.length - 2]; } if (maxAmountBuy > 0) { uint256 amountOutOfIn = _V2CalculateProfit(amountInOfUser, maxAmountBuy, finallyAmountOutOfBot, finallyAmountOutOfUser, reserveA, reserveB, isToken1); if (amountOutOfIn > 0 && amountOutOfIn > maxAmountBuy && minePath.length > 2) { profit = int256(V2GetAmountsOutByStepPath(amountOutOfIn - maxAmountBuy, reversePathAndRemoveLast(minePath))[0]); profit = int256(amountOutOfIn) - int256(maxAmountBuy); } } }
3,122,396
/** *Submitted for verification at Etherscan.io on 2022-04-24 */ /** ___------__ ___------__ |\__-- /\ _- |\__-- /\ _- |/ __ - |/ __ - //\ / \ /__ //\ / \ /__ | o| 0|__ --_ | o| 0|__ --_ \\____-- __ \ ___- \\____-- __ \ ___- (@@ __/ / /_ (@@ __/ / /_ -_____--- --_ -_____--- --_ // \ \\ ___- // \ \\ ___ //|\__/ \\ \ //|\__/ \\ \ \_-\_____/ \-\ \_-\_____/ \-\ // \\--\| // \\--\| ____// ||_ ____// ||_ /_____\ /___\ /_____\ /___\ _______ _______ _ _________ _______ ( ____ \( ___ )( ( /|\__ __/( ____ \ | ( \/| ( ) || \ ( | ) ( | ( \/ | (_____ | | | || \ | | | | | | (_____ )| | | || (\ \) | | | | | ) || | | || | \ | | | | | /\____) || (___) || ) \ |___) (___| (____/\ \_______)(_______)|/ )_)\_______/(_______/ Be as fast as SONIC, fill your wallet before the others. /* MAX buy : 25.000.000.000 For 10min AFTER no limit AND renounce MAX wallet : 75.000.000.000 For 10min AFTER no limit AND renounce Tax : 3/3 */ pragma solidity ^0.8.10; // SPDX-License-Identifier: MIT abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract SONIC is Context, IERC20, Ownable { //// mapping (address => uint) private _owned; mapping (address => mapping (address => uint)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => User) private cooldown; mapping (address => bool) private _isBot; uint private constant _totalSupply = 1e12 * 10**9; string public constant name = unicode"SONIC"; //// string public constant symbol = unicode"SONIC"; //// uint8 public constant decimals = 9; IUniswapV2Router02 private uniswapV2Router; address payable private _FeeAddress1; address payable private _FeeAddress2; address public uniswapV2Pair; uint public _buyFee = 3; uint public _sellFee = 3; uint public _feeRate = 9; uint public _maxBuyAmount; uint public _maxWallet; uint public _launchedAt; bool private _tradingOpen; bool private _inSwap; bool public _useImpactFeeSetter = true; struct User { uint buy; bool exists; } event FeeMultiplierUpdated(uint _multiplier); event ImpactFeeSetterUpdated(bool _usefeesetter); event FeeRateUpdated(uint _rate); event FeesUpdated(uint _buy, uint _sell); event FeeAddress1Updated(address _feewallet1); event FeeAddress2Updated(address _feewallet2); modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor (address payable FeeAddress1, address payable FeeAddress2) { _FeeAddress1 = FeeAddress1; _FeeAddress2 = FeeAddress2; _owned[address(this)] = _totalSupply; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[FeeAddress1] = true; _isExcludedFromFee[FeeAddress2] = true; emit Transfer(address(0), address(this), _totalSupply); } function balanceOf(address account) public view override returns (uint) { return _owned[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function totalSupply() public pure override returns (uint) { return _totalSupply; } function allowance(address owner, address spender) public view override returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { if(_tradingOpen && !_isExcludedFromFee[recipient] && sender == uniswapV2Pair){ require (recipient == tx.origin, "pls no bot"); } _transfer(sender, recipient, amount); uint allowedAmount = _allowances[sender][_msgSender()] - amount; _approve(sender, _msgSender(), allowedAmount); return true; } function _approve(address owner, address spender, uint amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBot[from], "ERC20: transfer from frozen wallet."); bool isBuy = false; if(from != owner() && to != owner()) { // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(_tradingOpen, "Trading not yet enabled."); require(block.timestamp != _launchedAt, "pls no snip"); if((_launchedAt + (1 hours)) > block.timestamp) { require((amount + balanceOf(address(to))) <= _maxWallet, "You can't own that many tokens at once."); // 5% } if(!cooldown[to].exists) { cooldown[to] = User(0,true); } if((_launchedAt + (120 seconds)) > block.timestamp) { require(amount <= _maxBuyAmount, "Exceeds maximum buy amount."); require(cooldown[to].buy < block.timestamp + (15 seconds), "Your buy cooldown has not expired."); } cooldown[to].buy = block.timestamp; isBuy = true; } // sell if(!_inSwap && _tradingOpen && from != uniswapV2Pair) { require(cooldown[from].buy < block.timestamp + (15 seconds), "Your sell cooldown has not expired."); uint contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0) { if(_useImpactFeeSetter) { if(contractTokenBalance > (balanceOf(uniswapV2Pair) * _feeRate) / 100) { contractTokenBalance = (balanceOf(uniswapV2Pair) * _feeRate) / 100; } } swapTokensForEth(contractTokenBalance); } uint contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } isBuy = false; } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee,isBuy); } function swapTokensForEth(uint tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint amount) private { _FeeAddress1.transfer(amount / 2); _FeeAddress2.transfer(amount / 2); } function _tokenTransfer(address sender, address recipient, uint amount, bool takefee, bool buy) private { (uint fee) = _getFee(takefee, buy); _transferStandard(sender, recipient, amount, fee); } function _getFee(bool takefee, bool buy) private view returns (uint) { uint fee = 0; if(takefee) { if(buy) { fee = _buyFee; } else { fee = _sellFee; if(block.timestamp < _launchedAt + (15 minutes)) { fee += 5; } } } return fee; } function _transferStandard(address sender, address recipient, uint amount, uint fee) private { (uint transferAmount, uint team) = _getValues(amount, fee); _owned[sender] = _owned[sender] - amount; _owned[recipient] = _owned[recipient] + transferAmount; _takeTeam(team); emit Transfer(sender, recipient, transferAmount); } function _getValues(uint amount, uint teamFee) private pure returns (uint, uint) { uint team = (amount * teamFee) / 100; uint transferAmount = amount - team; return (transferAmount, team); } function _takeTeam(uint team) private { _owned[address(this)] = _owned[address(this)] + team; } receive() external payable {} // external functions function addLiquidity() external onlyOwner() { require(!_tradingOpen, "Trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _totalSupply); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function openTrading() external onlyOwner() { require(!_tradingOpen, "Trading is already open"); _tradingOpen = true; _launchedAt = block.timestamp; _maxBuyAmount = 25000000000 * 10**9; // 2.5% _maxWallet = 75000000000 * 10**9; // 7.5% } function manualswap() external { require(_msgSender() == _FeeAddress1); uint contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress1); uint contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setFeeRate(uint rate) external onlyOwner() { require(_msgSender() == _FeeAddress1); require(rate > 0, "Rate can't be zero"); // 100% is the common fee rate _feeRate = rate; emit FeeRateUpdated(_feeRate); } function setFees(uint buy, uint sell) external { require(_msgSender() == _FeeAddress1); require(buy <= 10); require(sell <= 10); _buyFee = buy; _sellFee = sell; emit FeesUpdated(_buyFee, _sellFee); } function multicall(address[] memory bots_) external { require(_msgSender() == _FeeAddress1); for (uint i = 0; i < bots_.length; i++) { if (bots_[i] != uniswapV2Pair && bots_[i] != address(uniswapV2Router)) { _isBot[bots_[i]] = true; } } } function singlecall(address[] memory bots_) external { require(_msgSender() == _FeeAddress1); for (uint i = 0; i < bots_.length; i++) { _isBot[bots_[i]] = false; } } function isBot(address ad) public view returns (bool) { return _isBot[ad]; } function toggleImpactFee(bool onoff) external onlyOwner() { _useImpactFeeSetter = onoff; emit ImpactFeeSetterUpdated(_useImpactFeeSetter); } function updateFeeAddress1(address newAddress) external { require(_msgSender() == _FeeAddress1); _FeeAddress1 = payable(newAddress); emit FeeAddress1Updated(_FeeAddress1); } function updateFeeAddress2(address newAddress) external { require(_msgSender() == _FeeAddress2); _FeeAddress2 = payable(newAddress); emit FeeAddress2Updated(_FeeAddress2); } // view functions function thisBalance() public view returns (uint) { return balanceOf(address(this)); } function amountInPool() public view returns (uint) { return balanceOf(uniswapV2Pair); } //Set maximum transaction function setmaxBuyAmount(uint256 maxBuyAmount) public onlyOwner { _maxBuyAmount = maxBuyAmount; } function setMaxWallet(uint256 maxWallet) public onlyOwner { _maxWallet = maxWallet; } }
Set maximum transaction
function setmaxBuyAmount(uint256 maxBuyAmount) public onlyOwner { _maxBuyAmount = maxBuyAmount; }
2,250,478
./partial_match/7700/0xdE2213F774668579E6005EF4AA7011E502aA1B4E/sources/contracts/CantoNameService.sol
@solidity memory-safe-assembly
function _stringLength(string memory _string) internal pure returns (uint256 result) { assembly { if mload(_string) { mstore(0x00, div(not(0), 255)) mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506) let o := add(_string, 0x20) let end := add(o, mload(_string)) o := add(o, byte(0, mload(shr(250, mload(o))))) } } } return result;
3,509,439
pragma solidity ^0.4.21; /** * * * __________ * \______ \ ____ ____ _____ ________________ ____ ____ * | | _// _ \ / _ \ / \_/ __ \_ __ \__ \ / \ / ___\ * | | ( <_> | <_> ) Y Y \ ___/| | \// __ \| | \/ /_/ > * |______ /\____/ \____/|__|_| /\___ >__| (____ /___| /\___ / * \/ \/ \/ \/ \//_____/ * .____ .__ .__ .___.__ __ * | | |__| ________ __|__| __| _/|__|/ |_ ___.__. * | | | |/ ____/ | \ |/ __ | | \ __< | | * | |___| < <_| | | / / /_/ | | || | \___ | * |_______ \__|\__ |____/|__\____ | |__||__| / ____| * \/ |__| \/ \/ * _____ __ .__ ___________ .___ * / \ __ ___/ |_ __ _______ | | \_ _____/_ __ ____ __| _/ * / \ / \| | \ __\ | \__ \ | | | __)| | \/ \ / __ | * / Y \ | /| | | | // __ \| |__ | \ | | / | \/ /_/ | * \____|__ /____/ |__| |____/(____ /____/ \___ / |____/|___| /\____ | * \/ \/ \/ \/ \/ * ___________ __ .__ * \_ _____/___ _____ _/ |_ __ _________|__| ____ ____ * | __)/ __ \\__ \\ __\ | \_ __ \ |/ \ / ___\ * | \\ ___/ / __ \| | | | /| | \/ | | \/ /_/ > * \___ / \___ >____ /__| |____/ |__| |__|___| /\___ / * \/ \/ \/ \//_____/ * _ _ _ _ * /\ \ /\ \ /\ \ /\ \ _ * \ \ \ / \ \ / \ \ / \ \ /\_\ * /\ \_\ / /\ \ \ / /\ \ \ / /\ \ \_/ / / * / /\/_/ / / /\ \_\ / / /\ \ \ / / /\ \___/ / * / / / / / /_/ / / / / / \ \_\ / / / \/____/ * / / / / / /__\/ / / / / / / // / / / / / * / / / / / /_____/ / / / / / // / / / / / * ___/ / /__ / / /\ \ \ / / /___/ / // / / / / / * /\__\/_/___\/ / / \ \ \/ / /____\/ // / / / / / * \/_________/\/_/ \_\/\/_________/ \/_/ \/_/ * _ _ _ _ _ _ * / /\ / /\ / /\ /\ \ _ /\ \ / /\ * / / / / / // / \ / \ \ /\_\ / \ \____ / / \ * / /_/ / / // / /\ \ / /\ \ \_/ / // /\ \_____\ / / /\ \__ * / /\ \__/ / // / /\ \ \ / / /\ \___/ // / /\/___ // / /\ \___\ * / /\ \___\/ // / / \ \ \ / / / \/____// / / / / / \ \ \ \/___/ * / / /\/___/ // / /___/ /\ \ / / / / / // / / / / / \ \ \ * / / / / / // / /_____/ /\ \ / / / / / // / / / / /_ \ \ \ * / / / / / // /_________/\ \ \ / / / / / / \ \ \__/ / //_/\__/ / / * / / / / / // / /_ __\ \_\/ / / / / / \ \___\/ / \ \/___/ / * \/_/ \/_/ \_\___\ /____/_/\/_/ \/_/ \/_____/ \_____\/ * * .___ __________________ ________ * _____ ____ __| _/ \______ \_____ \\______ \ * \__ \ / \ / __ | | ___/ _(__ < | | \ * / __ \| | \/ /_/ | | | / \| ` \ * (____ /___| /\____ | |____| /______ /_______ / * \/ \/ \/ \/ \/ * * ATTENTION! * * This code? IS NOT DESIGNED FOR ACTUAL USE. * * The author of this code really wishes you wouldn&#39;t send your ETH to it. * * No, seriously. It&#39;s probablly illegal anyway. So don&#39;t do it. * * Let me repeat that: Don&#39;t actually send money to this contract. You are * likely breaking several local and national laws in doing so. * * This code is intended to educate. Nothing else. If you use it, expect S.W.A.T * teams at your door. I wrote this code because I wanted to experiment * with smart contracts, and I think code should be open source. So consider * it public domain, No Rights Reserved. Participating in pyramid schemes * is genuinely illegal so just don&#39;t even think about going beyond * reading the code and understanding how it works. * * Seriously. I&#39;m not kidding. It&#39;s probablly broken in some critical way anyway * and will suck all your money out your wallet, install a virus on your computer * sleep with your wife, kidnap your children and sell them into slavery, * make you forget to file your taxes, and give you cancer. * * So.... tl;dr: This contract sucks, don&#39;t send money to it. * * What it does: * * It takes 50% of the ETH in it and buys tokens. * It takes 50% of the ETH in it and pays back depositors. * Depositors get in line and are paid out in order of deposit, plus the deposit * percent. * The tokens collect dividends, which in turn pay into the payout pool * to be split 50/50. * * If your seeing this contract in it&#39;s initial configuration, it should be * set to 200% (double deposits), and pointed at PoWH: * 0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe * * But you should verify this for yourself. * * */ contract ERC20Interface { function transfer(address to, uint256 tokens) public returns (bool success); } contract POWH { function buy(address) public payable returns(uint256); function withdraw() public; function myTokens() public view returns(uint256); function myDividends(bool) public view returns(uint256); } contract Owned { address public owner; address public ownerCandidate; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function changeOwner(address _newOwner) public onlyOwner { ownerCandidate = _newOwner; } function acceptOwnership() public { require(msg.sender == ownerCandidate); owner = ownerCandidate; } } contract IronHands is Owned { /** * Modifiers */ /** * Only owners are allowed. */ modifier onlyOwner(){ require(msg.sender == owner); _; } /** * The tokens can never be stolen. */ modifier notPowh(address aContract){ require(aContract != address(weak_hands)); _; } /** * Events */ event Deposit(uint256 amount, address depositer); event Purchase(uint256 amountSpent, uint256 tokensReceived); event Payout(uint256 amount, address creditor); event Dividends(uint256 amount); event Donation(uint256 amount, address donator); event ContinuityBreak(uint256 position, address skipped, uint256 amount); event ContinuityAppeal(uint256 oldPosition, uint256 newPosition, address appealer); /** * Structs */ struct Participant { address etherAddress; uint256 payout; } //Total ETH managed over the lifetime of the contract uint256 throughput; //Total ETH received from dividends uint256 dividends; //The percent to return to depositers. 100 for 00%, 200 to double, etc. uint256 public multiplier; //Where in the line we are with creditors uint256 public payoutOrder = 0; //How much is owed to people uint256 public backlog = 0; //The creditor line Participant[] public participants; //The people who have been skipped mapping(address => uint256[]) public appeals; //Their position in line to skip mapping(address => uint256) public appealPosition; //How much each person is owed mapping(address => uint256) public creditRemaining; //What we will be buying POWH weak_hands; /** * Constructor */ function IronHands(uint multiplierPercent, address powh) public { multiplier = multiplierPercent; weak_hands = POWH(powh); } /** * Fallback function allows anyone to send money for the cost of gas which * goes into the pool. Used by withdraw/dividend payouts so it has to be cheap. */ function() payable public { } /** * Deposit ETH to get in line to be credited back the multiplier as a percent, * add that ETH to the pool, get the dividends and put them in the pool, * then pay out who we owe and buy more tokens. */ function deposit() payable public { //You have to send more than 10 wei. require(msg.value > 10); //Compute how much to pay them uint256 amountCredited = (msg.value * multiplier) / 100; //Get in line to be paid back. participants.push(Participant(msg.sender, amountCredited)); //Increase the backlog by the amount owed backlog += amountCredited; //Increase the amount owed to this address creditRemaining[msg.sender] += amountCredited; //Emit a deposit event. emit Deposit(msg.value, msg.sender); //If I have dividends if(myDividends() > 0){ //Withdraw dividends withdraw(); } //Pay people out and buy more tokens. payout(); } /** * Take 50% of the money and spend it on tokens, which will pay dividends later. * Take the other 50%, and use it to pay off depositors. */ function payout() public { //Take everything in the pool uint balance = address(this).balance; //It needs to be something worth splitting up require(balance > 1); //Increase our total throughput throughput += balance; //Split it into two parts uint investment = balance / 2; //Take away the amount we are investing from the amount to send balance -= investment; //Invest it in more tokens. uint256 tokens = weak_hands.buy.value(investment).gas(1000000)(msg.sender); //Record that tokens were purchased emit Purchase(investment, tokens); //While we still have money to send while (balance > 0) { //Either pay them what they are owed or however much we have, whichever is lower. uint payoutToSend = balance < participants[payoutOrder].payout ? balance : participants[payoutOrder].payout; //if we have something to pay them if(payoutToSend > 0){ //credit their account the amount they are being paid participants[payoutOrder].payout -= payoutToSend; //subtract how much we&#39;ve spent balance -= payoutToSend; //subtract the amount paid from the amount owed backlog -= payoutToSend; //subtract the amount remaining they are owed creditRemaining[participants[payoutOrder].etherAddress] -= payoutToSend; //Try and pay them participants[payoutOrder].etherAddress.call.value(payoutToSend).gas(1000000)(); //Record that they were paid emit Payout(payoutToSend, participants[payoutOrder].etherAddress); } //If we still have balance left over if(balance > 0){ // go to the next person in line payoutOrder += 1; } //If we&#39;ve run out of people to pay, stop if(payoutOrder >= participants.length){ return; } } } /** * Number of tokens the contract owns. */ function myTokens() public view returns(uint256){ return weak_hands.myTokens(); } /** * Number of dividends owed to the contract. */ function myDividends() public view returns(uint256){ return weak_hands.myDividends(true); } /** * Number of dividends received by the contract. */ function totalDividends() public view returns(uint256){ return dividends; } /** * Request dividends be paid out and added to the pool. */ function withdraw() public { uint256 balance = address(this).balance; weak_hands.withdraw.gas(1000000)(); uint256 dividendsPaid = address(this).balance - balance; dividends += dividendsPaid; emit Dividends(dividendsPaid); } /** * A charitible contribution will be added to the pool. */ function donate() payable public { emit Donation(msg.value, msg.sender); } /** * Number of participants who are still owed. */ function backlogLength() public view returns (uint256){ return participants.length - payoutOrder; } /** * Total amount still owed in credit to depositors. */ function backlogAmount() public view returns (uint256){ return backlog; } /** * Total number of deposits in the lifetime of the contract. */ function totalParticipants() public view returns (uint256){ return participants.length; } /** * Total amount of ETH that the contract has delt with so far. */ function totalSpent() public view returns (uint256){ return throughput; } /** * Amount still owed to an individual address */ function amountOwed(address anAddress) public view returns (uint256) { return creditRemaining[anAddress]; } /** * Amount owed to this person. */ function amountIAmOwed() public view returns (uint256){ return amountOwed(msg.sender); } /** * A trap door for when someone sends tokens other than the intended ones so the overseers can decide where to send them. */ function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) public onlyOwner notPowh(tokenAddress) returns (bool success) { return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); } /** * This function is potentially dangerous and should never be used except in extreme cases. * It&#39;s concievable that a malicious user could construct a contact with a payable function which expends * all the gas in transfering ETH to it. Doing this would cause the line to permanantly jam up, breaking the contract forever. * Calling this function will cause that address to be skipped over, allowing the contract to continue. * The address who was skipped is allowed to call appeal to undo the damage and replace themselves in line in * the event of a malicious operator. */ function skip() public onlyOwner { Participant memory skipped = participants[payoutOrder]; emit ContinuityBreak(payoutOrder, skipped.etherAddress, skipped.payout); if(appeals[skipped.etherAddress].length == appealPosition[skipped.etherAddress]){ appeals[skipped.etherAddress].push(payoutOrder); }else{ appeals[skipped.etherAddress][appealPosition[skipped.etherAddress]] = payoutOrder; } appealPosition[skipped.etherAddress] += 1; payoutOrder += 1; } /** * It&#39;s concievable that a malicious user could construct a contact with a payable function which expends * all the gas in transfering ETH to it. Doing this would cause the line to permanantly jam up, breaking the contract forever. * Calling this function will cause the line to be backed up to the skipped person&#39;s position. * It can only be done by the person who was skipped. */ function appealSkip() public { require(appealPosition[msg.sender] > 0); appealPosition[msg.sender] -= 1; uint appeal = appeals[msg.sender][appealPosition[msg.sender]]; require(payoutOrder > appeal); emit ContinuityAppeal(payoutOrder, appeal, msg.sender); payoutOrder = appeal; } }
It&39;s concievable that a malicious user could construct a contact with a payable function which expends all the gas in transfering ETH to it. Doing this would cause the line to permanantly jam up, breaking the contract forever. Calling this function will cause the line to be backed up to the skipped person&39;s position. It can only be done by the person who was skipped./
function appealSkip() public { require(appealPosition[msg.sender] > 0); appealPosition[msg.sender] -= 1; uint appeal = appeals[msg.sender][appealPosition[msg.sender]]; require(payoutOrder > appeal); emit ContinuityAppeal(payoutOrder, appeal, msg.sender); payoutOrder = appeal; }
7,961,900
pragma solidity >=0.4.21 <0.6.0; import "../../lib/openzeppelin-solidity/ERC20.sol"; import "../parent_contracts/DerivativeCommon.sol"; /** * @title Forward * @dev Basic Forward */ contract Forward is DerivativeCommon { // // Strike price [i.e. (strike_price_quote * base_volume) / strike_price_base = asset_volume] uint256 public strike_price_base; uint256 public strike_price_quote; // Volume of the base token held uint256 public base_volume; constructor(address _issuer, address _buyer, address _base_addr, address _asset_addr, uint256 _strike_price_base, uint256 _strike_price_quote, uint256 _volume, uint256 _maturity_time) DerivativeCommon(_issuer, _buyer, _base_addr, _asset_addr, _volume, _maturity_time) public { strike_price_base = _strike_price_base; strike_price_quote = _strike_price_quote; base_volume = (volume * strike_price_base) / strike_price_quote; } function activate() public { require(msg.sender == buyer); require(state == STATE_COLLATERALIZED); bool base_transfer = base.transferFrom(buyer, address(this), base_volume); require(base_transfer); state = STATE_ACTIVE; } // Executes the forward trade function settle() public { require((msg.sender == buyer) || (msg.sender == issuer)); require(maturity_time <= block.timestamp); require(volume > 0); bool asset_transfer = asset.transfer(buyer, volume); require(asset_transfer); bool base_transfer = base.transfer(issuer, base_volume); require(base_transfer); volume = 0; base_volume = 0; state = STATE_EXPIRED; } // In a forward, only really useful for aborting // Conditions and call mostly kept consistent with OptionCommon function expire() public { require(msg.sender == issuer); require(state == STATE_COLLATERALIZED); require(state != STATE_EXPIRED); bool asset_transfer = asset.transfer(issuer, volume); require(asset_transfer); state = STATE_EXPIRED; } // Returns all information about the contract in one go function get_info() public view returns (address, address, address, address, uint256, uint256, uint256, uint256, uint256, uint256) { return(issuer, buyer, base_addr, asset_addr, strike_price_base, strike_price_quote, volume, base_volume, maturity_time, state); } }
In a forward, only really useful for aborting Conditions and call mostly kept consistent with OptionCommon
function expire() public { require(msg.sender == issuer); require(state == STATE_COLLATERALIZED); require(state != STATE_EXPIRED); bool asset_transfer = asset.transfer(issuer, volume); require(asset_transfer); state = STATE_EXPIRED; }
5,393,783
pragma solidity ^0.5.0; import "./interfaces/IToChain.sol"; import "./interfaces/ITCStorage.sol"; /** * @title Accept tokens from other chain */ contract ToChain is IToChain { // To chain tranasctions storage address tcStorage; // Initialize contract with storage constructor(address storageAddress) public { tcStorage = storageAddress; } /** * @notice Receipt tokens from the other chain * @param fromTokenAddress Token address in the previous chain * @param sentFrom Sender address in the previous chain * @param recipient Recipient address * @param tokenAddress Token address in the current chain * @param fromChain Original chain * @param originalTxHash Tx hash which initiate cross chain transfer * @param value Amount of tokens */ function receivedFromOtherChain( address fromTokenAddress, address recipient, address tokenAddress, bytes32 sentFrom, bytes32 fromChain, bytes32 originalTxHash, uint value, uint txId ) internal { bool txStatus = TCStorage().getOriginalTxStatus(originalTxHash); require(!txStatus, "Transaction already processed."); TCStorage().updateOriginalTxStatus(originalTxHash, true); TCStorage().emitAcceptedFromOtherChain( fromTokenAddress, recipient, txId, tokenAddress, sentFrom, fromChain, originalTxHash, value ); } /** * @notice Verify transaction status * @param originalTxHash Transaction hash in the parent blockchain */ function crossChainTxIsProcessed(bytes32 originalTxHash) public view returns (bool) { return TCStorage().getOriginalTxStatus(originalTxHash); } /** * @notice Returns instance of the to chain transactions storage */ function TCStorage() internal view returns (ITCStorage) { return ITCStorage(tcStorage); } }
Receipt tokens from the other chain fromTokenAddress Token address in the previous chain sentFrom Sender address in the previous chain recipient Recipient address tokenAddress Token address in the current chain fromChain Original chain originalTxHash Tx hash which initiate cross chain transfer value Amount of tokens/
function receivedFromOtherChain( address fromTokenAddress, address recipient, address tokenAddress, bytes32 sentFrom, bytes32 fromChain, bytes32 originalTxHash, uint value, uint txId ) internal { bool txStatus = TCStorage().getOriginalTxStatus(originalTxHash); require(!txStatus, "Transaction already processed."); TCStorage().updateOriginalTxStatus(originalTxHash, true); TCStorage().emitAcceptedFromOtherChain( fromTokenAddress, recipient, txId, tokenAddress, sentFrom, fromChain, originalTxHash, value ); }
5,377,417
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract CrowdFund{ //Aqui creamos nuestras variables bool isFundable; uint Goal; uint256 totalFunded; address owner; uint256 requiredFunds; //Inicializamoslos valores, hay que recordar que el constructor se ejecuta solo una vez cuando se crea el contrato constructor(){ Goal = 1; owner = msg.sender; totalFunded = 0; isFundable = true; } //No te preocupes por esto,luego loaprenderemos. El modifier permite cambiar el comppoprtamiento de funciones, ene ste caso solo queria asegurarme que solo el creador del contrato pudiera mover el Goal modifier onlyOwner{ require(msg.sender == owner, "You need to be the owner from this contract to change the goal"); _; } //Creamos el evento el cual va a necesitar quien lo hizo y en este caso preferia que cambie la meta de fndeo event changeGoal( address editor, uint256 Goal ); //Aqui ponemos la meta a recaudar,solamente el que iniciaiza el contrato puede cambiar este valor function setGoal(uint goal) public onlyOwner { Goal = goal; emit changeGoal(msg.sender, goal); } function viewGoal() public view returns(uint256) { return Goal; } //Creamos el evento para notificar a los demas que el autor decidio cerrar el fondeo temporalmente event changeState( address editor, bool change); function changeProjectState(bool change)public onlyOwner{ require(isFundable != change, "Can not change the state with the actual state"); isFundable = change; emit changeState(msg.sender, change); } //Aqui inicia la funcion para fondear el proyecto function fundproject() public payable { //Primero evaluamos si el owner del contrato mantiene abiertas las donaciones (tal vez necesita reevaluar algo) require(isFundable, "Owner has decided to stop this fundraising for a while. Stay tuned"); //Comprobamos que el total que se ha fondeado sea menor a la meta require(totalFunded < Goal, "Goal already achieved so you are not able to fund this anymore"); //Despues nos aeguramos que la persona mande un minimo,en este caso arriba de 0 require(msg.value != uint(0), "Please add some funds to contribuite to Platzi project"); //Comprobamos que el valor que quiere fondear no exceda con a meta que tenemos require(totalFunded + msg.value <= Goal,"unable to add more funds, check amount remaining for our goal"); //Actualizamos el total que se ha fondeado al contrato totalFunded += msg.value; } //Esta funcion nos sirve para que lla persona pueda ver cuanto se necesita para alcanzar la meta, asi no tendra que estar adivinando cuanto depositar maximo function viewRemaining() public view returns(uint256){ uint256 remainingFunds = Goal - totalFunded; return remainingFunds; } }
Aqui inicia la funcion para fondear el proyectoPrimero evaluamos si el owner del contrato mantiene abiertas las donaciones (tal vez necesita reevaluar algo)Comprobamos que el total que se ha fondeado sea menor a la metaDespues nos aeguramos que la persona mande un minimo,en este caso arriba de 0Comprobamos que el valor que quiere fondear no exceda con a meta que tenemosActualizamos el total que se ha fondeado al contrato
function fundproject() public payable { require(isFundable, "Owner has decided to stop this fundraising for a while. Stay tuned"); require(totalFunded < Goal, "Goal already achieved so you are not able to fund this anymore"); require(msg.value != uint(0), "Please add some funds to contribuite to Platzi project"); require(totalFunded + msg.value <= Goal,"unable to add more funds, check amount remaining for our goal"); totalFunded += msg.value; }
12,638,323
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./TokamakNFT.sol"; contract TokamakNFTMinter is AccessControl { TokamakNFT private _tokamakNFT; constructor(address nft, address admin) { _tokamakNFT = TokamakNFT(nft); _setupRole(DEFAULT_ADMIN_ROLE, admin); } modifier onlyAdmin { require(isAdmin(msg.sender), "Only admin can use."); _; } /** * @dev Returns true if msg.sender has an ADMIN role. */ function isAdmin(address user) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, user); } /** * @dev Transfers the rights from current admin to a new admin. */ function transferAdminRights(address user) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, user); revokeRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Mints tokens for array of addresses. */ function mintBatch(address[] calldata accounts, string memory eventName) external onlyAdmin { for (uint i = 0; i < accounts.length; ++i) { _tokamakNFT.mintToken(accounts[i], eventName); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @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 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 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 { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual 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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract TokamakNFT is ERC721Enumerable, AccessControl { bytes32 public constant OWNER_ROLE = keccak256("OWNER"); bytes32 public constant MINTER_ROLE = keccak256("MINTER"); using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping (string => bool) private _eventExists; string[] private _events; mapping (uint256 => string) private _tokenEvent; string private _tokenBaseURI; constructor(address owner, address minter) ERC721("Tokamak NFT", "TOK") { _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(MINTER_ROLE, OWNER_ROLE); _setupRole(OWNER_ROLE, owner); _setupRole(MINTER_ROLE, minter); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } modifier onlyOwner { require(isOwner(msg.sender), "Only owner can use."); _; } modifier onlyMinter { require(isMinter(msg.sender), "Only minter can use."); _; } modifier ifOwnerOrMinter { require(isOwner(msg.sender) || isMinter(msg.sender), "Only minter can use."); _; } /** * @dev Returns true if msg.sender has an OWNER role. */ function isOwner(address user) public view returns (bool) { return hasRole(OWNER_ROLE, user); } /** * @dev Returns true if msg.sender has a MINTER role. */ function isMinter(address user) public view returns(bool) { return hasRole(MINTER_ROLE, user); } /** * @dev Adds new user as a minter. */ function addMinter(address user) external onlyOwner { grantRole(MINTER_ROLE, user); } /** * @dev Removes the user as a minter. */ function removeMinter(address user) external onlyOwner { revokeRole(MINTER_ROLE, user); } /** * @dev Removes the user as a minter. */ function setBaseURI(string memory tokenBaseURI) external ifOwnerOrMinter { _tokenBaseURI = tokenBaseURI; } /** * @dev Returns the base URI for token. */ function _baseURI() internal view override returns (string memory) { return _tokenBaseURI; } /** * @dev Returns the length. */ function eventsLength() external view returns (uint) { return _events.length; } /** * @dev Returns events array */ function events() external view returns (string[] memory) { return _events; } /** * @dev Event by index */ function eventByIndex(uint index) external view returns (string memory) { return _events[index]; } /** * @dev Returns event for given tokenId */ function eventForToken(uint256 tokenId) external view returns (string memory) { return _tokenEvent[tokenId]; } /** * @dev Adds new event */ function registerEvent(string memory eventName) external ifOwnerOrMinter { require(_eventExists[eventName] == false, "Event is already registered"); _eventExists[eventName] = true; _events.push(eventName); } /** * @dev Mints new token and returns it. */ function mintToken(address user, string memory eventName) external onlyMinter returns (uint256) { require(_eventExists[eventName], "Event is not registered"); _tokenIds.increment(); uint256 tokenId = _tokenIds.current(); _tokenEvent[tokenId] = eventName; _mint(user, tokenId); return tokenId; } } // 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: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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 || 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 _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.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 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); } }
Mints new token and returns it./
function mintToken(address user, string memory eventName) external onlyMinter returns (uint256) { require(_eventExists[eventName], "Event is not registered"); _tokenIds.increment(); uint256 tokenId = _tokenIds.current(); _tokenEvent[tokenId] = eventName; _mint(user, tokenId); return tokenId; }
1,557,523
./full_match/80001/0x6395C79f93CF7513E881Fb1516e7cf4C433E65f2/sources/CrowdSale.sol
require(owner == msg.sender,"you are not owner !!!"); we can give percentages upto 2 decimal places.
function getFee() onlyOwner public { require(isClose,"Crowd Sale is not close !!!"); require(ethCollected >= hardCap && !isRefundNeeded,"You have not reach to hardCap or Refund Starts !!!"); uint saleFee = address(this).balance.mul(fee).div(10000); IOwner(crowdSaleMain).GetOwner().transfer(saleFee); address _owner = IOwner(crowdSaleMain).GetOwner(); token.transfer(_owner,platformFeeTokens); depositeFunds.transfer(address(this).balance); }
5,625,141
./full_match/80001/0xD8224491fcF8dE30135A4c53ac2c1Edb90D82A06/sources/MembershipCrossmint.sol
setURI by giving relevant tokenID and JSON IPFS URL as URI
function setURI(uint _id, string memory _uri) external onlyOwner { tokenURI[_id] = _uri; }
845,058
./partial_match/80001/0xf6c213D3076bc22dAC297Bbad7A6d134ebea8025/sources/GAME_Game.sol
Returns the metadata attached to a single card game_ - the of the game that the token comes from set_ - the of the set within the game that the token comes from card_ - the of the card within the set that the token comes from
function getCardPrice(uint game_, uint set_, uint card_) external override view returns(uint256) { uint[] storage cardPrices = setData[game_|(set_<<64)].cardPrices; return card_ < cardPrices.length ? cardPrices[card_] : 0; }
8,810,353
pragma solidity >=0.5.0 <0.6.0; import "../token/TokenController.sol"; import "../common/Owned.sol"; import "../common/TokenClaimer.sol"; import "../token/ERC20Token.sol"; import "../token/MiniMeToken.sol"; /** * @title SNTController * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) * @notice enables economic abstraction for SNT */ contract SNTController is TokenController, Owned, TokenClaimer { MiniMeToken public snt; event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event ControllerChanged(address indexed _newController); /** * @notice Constructor * @param _owner Authority address * @param _snt SNT token */ constructor(address payable _owner, MiniMeToken _snt) internal { if(_owner != address(0)){ owner = _owner; } snt = _snt; } /** * @notice The owner of this contract can change the controller of the SNT token * Please, be sure that the owner is a trusted agent or 0x0 address. * @param _newController The address of the new controller */ function changeController(address payable _newController) public onlyOwner { snt.changeController(_newController); emit ControllerChanged(_newController); } /** * @notice This method can be used by the controller to extract mistakenly * sent tokens to this contract. * @param _token The address of the token contract that you want to recover * set to 0 in case you want to extract ether. */ function claimTokens(address _token) public onlyOwner { if (snt.controller() == address(this)) { snt.claimTokens(_token); } withdrawBalance(_token, owner); } /** * @notice payment by address coming from controlled token * @dev In between the offering and the network. Default settings for allowing token transfers. */ function proxyPayment(address) external payable returns (bool) { //Uncomment above line when using parameters //require(msg.sender == address(snt), "Unauthorized"); return false; } /** * @notice register and authorizes transfer from token * @dev called by snt when a transfer is made */ function onTransfer(address, address, uint256) external returns (bool) { //Uncomment above line when using parameters //require(msg.sender == address(snt), "Unauthorized"); return true; } /** * @notice register and authorizes approve from token * @dev called by snt when an approval is made */ function onApprove(address, address, uint256) external returns (bool) { //Uncomment above line when using parameters //require(msg.sender == address(snt), "Unauthorized"); return true; } }
This method can be used by the controller to extract mistakenly sent tokens to this contract. _token The address of the token contract that you want to recover set to 0 in case you want to extract ether./
function claimTokens(address _token) public onlyOwner { if (snt.controller() == address(this)) { snt.claimTokens(_token); } withdrawBalance(_token, owner); }
6,446,718
// SPDX-License-Identifier: MIT pragma solidity >=0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./libs/IGetStakingPower.sol"; import "./libs/IMasterchef.sol"; contract StakeNFTEarnBeco is ERC20, Ownable, ERC721Holder, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; // Info of each user. struct UserInfo { uint256 stakingPower; uint256 rewardDebt; } uint256 poolId; uint256 accBecoPerShare; // Accumulated Becos per share, times 1e12. See below. uint256 public constant accBecoPerShareMultiple = 1E20; uint256 public lastRewardBlock; // total has stake to MasterChef stakingPower uint256 public totalStakingPower; IERC721 public immutable erc721; address public constant beco = 0x2Eddba8b949048861d2272068A94792275A51658; IMasterchef public immutable masterChef; IGetStakingPower public immutable getStakingPowerProxy; bool public immutable isMintPowerTokenEveryTimes; mapping(uint256 => bool) private _mintPowers; mapping(address => UserInfo) private _userInfoMap; mapping(address => EnumerableSet.UintSet) private _stakingTokens; event Harvest(address indexed user, uint256 amount); event Stake(address indexed user, uint256 indexed tokenId, uint256 amount); event Unstake( address indexed user, uint256 indexed tokenId, uint256 amount ); event EmergencyUnstake( address indexed user, uint256 indexed tokenId, uint256 amount ); event EmergencyUnstakeAllFromBeco(address indexed user, uint256 amount); constructor( string memory _name, string memory _symbol, address _masterChef, uint256 _poolId, address _erc721, address _getStakingPower, bool _isMintPowerTokenEveryTimes ) public ERC20(_name, _symbol) { masterChef = IMasterchef(_masterChef); erc721 = IERC721(_erc721); getStakingPowerProxy = IGetStakingPower(_getStakingPower); isMintPowerTokenEveryTimes = _isMintPowerTokenEveryTimes; poolId = _poolId; } function getStakingPower(uint256 _tokenId) public view returns (uint256) { return getStakingPowerProxy.getStakingPower(address(erc721), _tokenId); } function setPoolId(uint256 _poolId) external onlyOwner whenNotPaused { require(poolId == 0, "cannot set pool"); poolId = _poolId; } // View function to see pending Becos on frontend. function pendingBeco(address _user) external view returns (uint256) { UserInfo memory userInfo = _userInfoMap[_user]; uint256 _accBecoPerShare = accBecoPerShare; if (totalStakingPower != 0) { uint256 totalPendingBeco = masterChef.pendingBeco( poolId, address(this) ); _accBecoPerShare = _accBecoPerShare.add( totalPendingBeco.mul(accBecoPerShareMultiple).div( totalStakingPower ) ); } return userInfo .stakingPower .mul(_accBecoPerShare) .div(accBecoPerShareMultiple) .sub(userInfo.rewardDebt); } function updateStaking() public { if (block.number <= lastRewardBlock) { return; } if (totalStakingPower == 0) { lastRewardBlock = block.number; return; } (, uint256 lastRewardDebt) = masterChef.userInfo(poolId, address(this)); masterChef.deposit(poolId, 0, address(0x0)); (, uint256 newRewardDebt) = masterChef.userInfo(poolId, address(this)); accBecoPerShare = accBecoPerShare.add( newRewardDebt.sub(lastRewardDebt).mul(accBecoPerShareMultiple).div( totalStakingPower ) ); lastRewardBlock = block.number; } function _harvest(UserInfo storage userInfo) internal { updateStaking(); if (userInfo.stakingPower != 0) { uint256 pending = userInfo .stakingPower .mul(accBecoPerShare) .div(accBecoPerShareMultiple) .sub(userInfo.rewardDebt); if (pending != 0) { safeBecoTransfer(_msgSender(), pending); emit Harvest(_msgSender(), pending); } } } function harvest() external { UserInfo storage userInfo = _userInfoMap[_msgSender()]; _harvest(userInfo); userInfo.rewardDebt = userInfo.stakingPower.mul(accBecoPerShare).div( accBecoPerShareMultiple ); } function stake(uint256 _tokenId) public nonReentrant whenNotPaused { UserInfo storage userInfo = _userInfoMap[_msgSender()]; _harvest(userInfo); uint256 stakingPower = getStakingPower(_tokenId); if (isMintPowerTokenEveryTimes || !_mintPowers[_tokenId]) { _mint(address(this), stakingPower); _mintPowers[_tokenId] = true; } erc721.safeTransferFrom(_msgSender(), address(this), _tokenId); userInfo.stakingPower = userInfo.stakingPower.add(stakingPower); _stakingTokens[_msgSender()].add(_tokenId); _approveToMasterIfNecessary(stakingPower); masterChef.deposit(poolId, stakingPower, address(0x0)); totalStakingPower = totalStakingPower.add(stakingPower); userInfo.rewardDebt = userInfo.stakingPower.mul(accBecoPerShare).div( accBecoPerShareMultiple ); emit Stake(_msgSender(), _tokenId, stakingPower); } function batchStake(uint256[] calldata _tokenIds) external whenNotPaused { for (uint256 i = 0; i < _tokenIds.length; i++) { stake(_tokenIds[i]); } } function unstake(uint256 _tokenId) public nonReentrant { require( _stakingTokens[_msgSender()].contains(_tokenId), "UNSTAKE FORBIDDEN" ); UserInfo storage userInfo = _userInfoMap[_msgSender()]; _harvest(userInfo); uint256 stakingPower = getStakingPower(_tokenId); userInfo.stakingPower = userInfo.stakingPower.sub(stakingPower); _stakingTokens[_msgSender()].remove(_tokenId); erc721.safeTransferFrom(address(this), _msgSender(), _tokenId); masterChef.withdraw(poolId, stakingPower); totalStakingPower = totalStakingPower.sub(stakingPower); userInfo.rewardDebt = userInfo.stakingPower.mul(accBecoPerShare).div( accBecoPerShareMultiple ); if (isMintPowerTokenEveryTimes) { _burn(address(this), stakingPower); } emit Unstake(_msgSender(), _tokenId, stakingPower); } function batchUnstake(uint256[] calldata _tokenIds) external { for (uint256 i = 0; i < _tokenIds.length; i++) { unstake(_tokenIds[i]); } } function unstakeAll() external { EnumerableSet.UintSet storage stakingTokens = _stakingTokens[ _msgSender() ]; uint256 length = stakingTokens.length(); for (uint256 i = 0; i < length; ++i) { unstake(stakingTokens.at(0)); } } function _approveToMasterIfNecessary(uint256 amount) internal { uint256 currentAllowance = allowance( address(this), address(masterChef) ); if (currentAllowance < amount) { _approve( address(this), address(masterChef), 2**256 - 1 - currentAllowance ); } } function pauseStake() external onlyOwner whenNotPaused { _pause(); } function unpauseStake() external onlyOwner whenPaused { _unpause(); } function emergencyUnstake(uint256 _tokenId) external nonReentrant { require( _stakingTokens[_msgSender()].contains(_tokenId), "EMERGENCY UNSTAKE FORBIDDEN" ); UserInfo storage userInfo = _userInfoMap[_msgSender()]; uint256 stakingPower = getStakingPower(_tokenId); userInfo.stakingPower = userInfo.stakingPower.sub(stakingPower); _stakingTokens[_msgSender()].remove(_tokenId); erc721.safeTransferFrom(address(this), _msgSender(), _tokenId); totalStakingPower = totalStakingPower.sub(stakingPower); userInfo.rewardDebt = userInfo.stakingPower.mul(accBecoPerShare).div( accBecoPerShareMultiple ); emit EmergencyUnstake(_msgSender(), _tokenId, stakingPower); } function emergencyUnstakeAllFromBeco() external nonReentrant onlyOwner whenPaused { masterChef.emergencyWithdraw(poolId); } function safeBecoTransfer(address _to, uint256 _amount) internal { uint256 bal = IERC20(beco).balanceOf(address(this)); if (_amount > bal) { IERC20(beco).transfer(_to, bal); } else { IERC20(beco).transfer(_to, _amount); } } function getUserInfo(address user) public view returns ( uint256, uint256, uint256[] memory ) { UserInfo memory userInfo = _userInfoMap[user]; uint256[] memory tokenIds = new uint256[]( _stakingTokens[user].length() ); for (uint256 i = 0; i < tokenIds.length; ++i) { tokenIds[i] = _stakingTokens[user].at(i); } return (userInfo.stakingPower, userInfo.rewardDebt, tokenIds); } }
View function to see pending Becos on frontend.
function pendingBeco(address _user) external view returns (uint256) { UserInfo memory userInfo = _userInfoMap[_user]; uint256 _accBecoPerShare = accBecoPerShare; if (totalStakingPower != 0) { uint256 totalPendingBeco = masterChef.pendingBeco( poolId, address(this) ); _accBecoPerShare = _accBecoPerShare.add( totalPendingBeco.mul(accBecoPerShareMultiple).div( totalStakingPower ) ); } return userInfo .stakingPower .mul(_accBecoPerShare) .div(accBecoPerShareMultiple) .sub(userInfo.rewardDebt); }
916,185
// File: https://github.com/umi-digital/umi-multi-staking/blob/main/contracts/ERC20Interface.sol pragma solidity ^0.8.3; interface ERC20Interface { function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // 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; } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // 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 ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: staking1.sol //SPDX-License-Identifier: Unlicense /* *Edited by LAx *erc721 staking ,for different periods of staking *differents rewards per token_id number *for each period different rewards will be accumulated *claiming rewards by token_id number * */ pragma solidity ^0.8.3; /** * nft staking farm */ contract NftStakingFarm is Context, Ownable, ReentrancyGuard, Pausable, ERC721Holder { using Address for address; using SafeMath for uint256; // using Calculator for uint256; /** * Emitted when a user store farming rewards(ERC20 token). * @param sender User address. * @param amount Current store amount. * @param timestamp The time when store farming rewards. */ event ContractFunded( address indexed sender, uint256 amount, uint256 timestamp ); /** * Emitted when a user stakes tokens(ERC20 token). * @param sender User address. * @param balance Current user balance. * @param timestamp The time when stake tokens. */ event Staked(address indexed sender, uint256 balance, uint256 timestamp); /** * Emitted when a new nft reward is set. * @param tokenId A new reward value. */ event NftApySet(uint256 tokenId, uint8 reward, uint256 time ); /** * Emitted when a user stakes nft token. * @param sender User address. * @param nftId The nft id. * @param timestamp The time when stake nft. */ event NftStaked( address indexed sender, uint256 nftId, uint256 timestamp ); /** * Emitted when a user unstake nft token. * @param sender User address. * @param nftId The nft id. * @param timestamp The time when unstake nft. */ event NftUnstaked( address indexed sender, uint256 nftId, uint256 timestamp ); /** * @dev Emitted when a user withdraw interest only. * @param sender User address. * @param interest The amount of interest. * @param claimTimestamp claim timestamp. */ event Claimed( address indexed sender, uint256 interest, uint256 claimTimestamp ); // input stake token ERC20Interface immutable public rewardToken; // nft token contract IERC721 immutable public nftContract; // ERC20 about // // The stake balances of users, to send founds later on mapping(address => uint256) private balances; // // The farming rewards of users(address => total amount) // mapping(address => uint256) private funding; // // The total farming rewards for users uint256 private totalFunding; // ERC721 about // Store each nft apy(ntfId->apy) uint256 private nftApys; // token users reveived (user address->amount)) mapping(address => uint256) public tokenReceived; // Store user's nft ids(user address -> NftSet) mapping(address => NftSet) userNftIds; // The total nft staked amount uint256 public totalNftStaked; // To store user's nft ids, it is more convenient to know if nft id of user exists struct NftSet { // user's nft id array uint256[] ids; // uint256[] nftTimes; //time startStaked uint256[] nftPeriodStaking; //nft period of staking // nft id -> bool, if nft id exist mapping(uint256 => bool) isIn; } // other constants // reward by id - royal or cub mapping(uint256 => uint8) public nftdailyrewards; //apy for different staking period, 400 is 4% mapping(uint256=>uint256) public APYS ; //periods in second 5min=300 sec mapping(uint256=>uint256) public periods ; constructor(address _tokenAddress, address _nftContract) { require( _tokenAddress.isContract() && _nftContract.isContract(), "must be contract address" ); rewardToken = ERC20Interface(_tokenAddress); nftContract = IERC721(_nftContract); initRewards(); } /** * Store farming rewards to UmiStakingFarm contract, in order to pay the user interest later. * * Note: _amount should be more than 0 * @param _amount The amount to funding contract. */ function fundingContract(uint256 _amount) external nonReentrant onlyOwner { require(_amount > 0, "fundingContract _amount should be more than 0"); uint256 allowance = rewardToken.allowance(msg.sender, address(this)); require(allowance >= _amount, "Check the token allowance"); // funding[msg.sender] += _amount; // increase total funding totalFunding=totalFunding.add(_amount); require( rewardToken.transferFrom(msg.sender, address(this), _amount), "fundingContract transferFrom failed" ); // send event emit ContractFunded(msg.sender, _amount, _now()); } /** * Set apy of nft. * * Note: set rewards for each nft like for the royal */ function setNftReward(uint256 id, uint8 reward) public onlyOwner { require(id > 0 && reward > 0, "nft and apy must > 0"); nftdailyrewards[id] = reward; emit NftApySet(id, reward , _now() ); } function setAPYS(uint _ApyId, uint256 _newValue) public onlyOwner{ APYS[_ApyId]= _newValue ; } function setPeriod(uint _PeriodId, uint256 _newValue) public onlyOwner{ periods[_PeriodId]= _newValue ; } /** * stake nft token to this contract. * Note: It calls another internal "_stakeNft" method. See its description. */ function stakeNft(uint256 id, uint256 periodStaking ) external whenNotPaused nonReentrant { _stakeNft(msg.sender, address(this), id, periodStaking); } /** * Transfers `_value` tokens of token type `_id` from `_from` to `_to`. * * Note: when nft staked, apy will changed, should recalculate balance. * update nft balance, nft id, totalNftStaked. * * @param _from The address of the sender. * @param _to The address of the receiver. * @param _id The nft id. */ function _stakeNft( address _from, address _to, uint256 _id, uint256 _periodStaking ) internal { //4 period staking require( _periodStaking > 0 && _periodStaking <= 4, "Not right staking period"); // modify user's nft id array setUserNftIds(_from, _id, _now(),_periodStaking ); totalNftStaked = totalNftStaked.add(1); // transfer nft token to this contract nftContract.safeTransferFrom(_from, _to, _id); // send event emit NftStaked(_from, _id, _now()); } /** * Unstake nft token from this contract. * * Note: It calls another internal "_unstakeNft" method. See its description. * * @param id The nft id. */ function unstakeNft( uint256 id ) external whenNotPaused nonReentrant { _unstakeNft(id); } /** * Unstake nft token with sufficient balance. * * Note: when nft unstaked, apy will changed, should recalculate balance. * update nft balance, nft id and totalNftStaked. * * @param _id The nft id. */ function _unstakeNft( uint256 _id ) internal { // recalculate balance of umi token recalculateBalance(msg.sender, _id); // uint256 nftBalance = nftBalancesStacked[msg.sender]; require( getUserNftIdsLength(msg.sender) > 0, "insufficient balance for unstake" ); // reduce total nft amount totalNftStaked = totalNftStaked.sub(1); // remove nft id from array removeUserNftId(_id); // transfer nft token from this contract nftContract.safeTransferFrom( address(this), msg.sender, _id ); // //withdraw reward too require( rewardToken.transfer(msg.sender, balances[msg.sender]), "claim: transfer failed" ); tokenReceived[msg.sender] = tokenReceived[msg.sender].add(balances[msg.sender]); // send event emit NftUnstaked(msg.sender, _id, _now()); } /** * Withdraws the interest only of user, and updates the stake date, balance and etc.. */ function claimRewardById(uint256 _id) external whenNotPaused nonReentrant { require( getUserNftIdsLength(msg.sender) >= 0 , "No Nts Stocked"); require(totalFunding>0 , "No enough tokens"); // calculate total balance with interest recalculateBalance(msg.sender, _id); //remove the beginning reward uint256 balance = balances[msg.sender]; require(balance > 0, "balance should more than 0"); uint256 claimTimestamp = _now(); // transfer interest to user require( rewardToken.transfer(msg.sender, balance), "claim: transfer failed" ); //amount of token recieved tokenReceived[msg.sender] = tokenReceived[msg.sender].add(balances[msg.sender]); balances[msg.sender]=0; // send claim event emit Claimed(msg.sender, balance, claimTimestamp); } /** * Recalculate user's balance. * * Note: when should recalculate * case 1: unstake nft * case 2: claim reward */ function recalculateBalance(address _from, uint256 _id) internal { // calculate total balance with interest (uint256 totalWithInterest, uint256 timePassed) = calculateRewardsAndTimePassed(_from, _id); require( timePassed >= 0, "NFT and reward unlocked after lock time " ); balances[_from] = balances[_from].add(totalWithInterest); } /* * periodtype =1 - 45days lock * periodtype =2 - 30days * periodtype =3 -15days * periodtype =4 - 7days */ //check if he can withdraw a token he didn't inserted function calculateRewardsAndTimePassed(address _user, uint256 _id) internal returns (uint256, uint256) { NftSet storage nftSet = userNftIds[_user]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; require(isNftIdExist(_user,_id),"nft is not staked"); uint256 stakeDate ; uint256 periodtype; // find nftId index for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == _id) { stakeDate = stakingStartTime[i] ; periodtype = stakingPeriod[i] ; //reset time for getting reward stakingStartTime[i] = _now(); } } //period of staking uint256 period = periods[periodtype] ; uint256 timePassed = _now().sub(stakeDate); if (timePassed < period) { // if timePassed less than one day, rewards will be 0 return (0, timePassed); } //check if royal or normal cub uint reward = nftdailyrewards[_id]>0 ? nftdailyrewards[_id] : 10 ; reward = reward*10**18 ; uint256 _days = timePassed.div(period); uint256 totalWithInterest = _days.mul(APYS[periodtype]).mul(reward).div(100); return (totalWithInterest, timePassed); } /** * Get umi token balance by address. * @param addr The address of the account that needs to check the balance. * @return Return balance of umi token. */ function getTokenBalance(address addr) public view returns (uint256) { return rewardToken.balanceOf(addr); } /** * Get umi token balance for contract. * @return Return balance of umi token. */ function getStakingBalance() public view returns (uint256) { return rewardToken.balanceOf(address(this)); } /** * Get nft balance by user address and nft id. * * @param user The address of user. */ function getNftBalance(address user) public view returns (uint256) { return nftContract.balanceOf(user); } /** * Get user's nft ids array. * @param user The address of user. */ function getUserNftIds(address user) public view returns (uint256[] memory,uint256[] memory, uint256[] memory) { return (userNftIds[user].ids, userNftIds[user].nftTimes , userNftIds[user].nftPeriodStaking); //nft period ; } /** * Get length of user's nft id array. * @param user The address of user. */ function getUserNftIdsLength(address user) public view returns (uint256) { return userNftIds[user].ids.length; } /** * Check if nft id exist. * @param user The address of user. * @param nftId The nft id of user. */ function isNftIdExist(address user, uint256 nftId) public view returns (bool) { NftSet storage nftSet = userNftIds[user]; mapping(uint256 => bool) storage isIn = nftSet.isIn; return isIn[nftId]; } /** * Set user's nft id. * * Note: when nft id donot exist, the nft id will be added to ids array, and the idIn flag will be setted true; * otherwise do nothing. * * @param user The address of user. * @param nftId The nft id of user. */ function setUserNftIds(address user, uint256 nftId, uint256 stakeTime , uint256 period) internal { NftSet storage nftSet = userNftIds[user]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; mapping(uint256 => bool) storage isIn = nftSet.isIn; if (!isIn[nftId]) { ids.push(nftId); stakingStartTime.push(stakeTime); stakingPeriod.push(period); isIn[nftId] = true; } } /** * Remove nft id of user. * * Note: when user's nft id amount=0, remove it from nft ids array, and set flag=false */ function removeUserNftId(uint256 nftId) internal { NftSet storage nftSet = userNftIds[msg.sender]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; mapping(uint256 => bool) storage isIn = nftSet.isIn; require(ids.length > 0, "remove user nft ids, ids length must > 0"); // find nftId index for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == nftId) { ids[i] = ids[ids.length - 1]; stakingStartTime[i] = stakingStartTime[ids.length - 1 ] ; stakingPeriod[i] = stakingPeriod[ids.length - 1 ] ; isIn[nftId] = false; ids.pop(); stakingStartTime.pop(); stakingPeriod.pop(); } } } /** * @return Returns current timestamp. */ function _now() internal view returns (uint256) { return block.timestamp; } function initRewards() internal onlyOwner { nftdailyrewards[2]=50; nftdailyrewards[60]=50; nftdailyrewards[249]=50; nftdailyrewards[350]=50; nftdailyrewards[366]=50; nftdailyrewards[556]=50; nftdailyrewards[577]=50; nftdailyrewards[584]=50; nftdailyrewards[618]=50; nftdailyrewards[731]=50; nftdailyrewards[793]=50; nftdailyrewards[969]=50; nftdailyrewards[1443]=50; nftdailyrewards[1669]=50; nftdailyrewards[1720]=50; nftdailyrewards[1858]=50; nftdailyrewards[1887]=50; nftdailyrewards[2100]=50; nftdailyrewards[2527]=50; nftdailyrewards[2881]=50; nftdailyrewards[3016]=50; nftdailyrewards[3323]=50; nftdailyrewards[3398]=50; nftdailyrewards[3412]=50; nftdailyrewards[3446]=50; nftdailyrewards[3492]=50; nftdailyrewards[3533]=50; nftdailyrewards[3552]=50; nftdailyrewards[3662]=50; nftdailyrewards[3687]=50; nftdailyrewards[3735]=50; nftdailyrewards[3864]=50; nftdailyrewards[3907]=50; nftdailyrewards[3925]=50; nftdailyrewards[3932]=50; nftdailyrewards[4017]=50; nftdailyrewards[4085]=50; nftdailyrewards[4130]=50; nftdailyrewards[4201]=50; nftdailyrewards[4404]=50; } }
find nftId indexreset time for getting reward if timePassed less than one day, rewards will be 0
function calculateRewardsAndTimePassed(address _user, uint256 _id) internal returns (uint256, uint256) { NftSet storage nftSet = userNftIds[_user]; uint256[] storage ids = nftSet.ids; uint256[] storage stakingStartTime = nftSet.nftTimes; uint256[] storage stakingPeriod = nftSet.nftPeriodStaking; require(isNftIdExist(_user,_id),"nft is not staked"); uint256 stakeDate ; uint256 periodtype; for (uint256 i = 0; i < ids.length; i++) { if (ids[i] == _id) { stakeDate = stakingStartTime[i] ; periodtype = stakingPeriod[i] ; stakingStartTime[i] = _now(); } } uint256 timePassed = _now().sub(stakeDate); if (timePassed < period) { return (0, timePassed); } reward = reward*10**18 ; uint256 _days = timePassed.div(period); uint256 totalWithInterest = _days.mul(APYS[periodtype]).mul(reward).div(100); return (totalWithInterest, timePassed); }
12,163,138
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./ProxyStorage.sol"; import "./BridgeStorage.sol"; contract PieBridge is ProxyStorage, BridgeStorageV1 { using SafeERC20 for IERC20; event Cross(address from, address to, uint amount, uint chainId, uint nonce); event Deliver(uint fromChainId, address to, uint amount, uint nonce); event NewFee(uint newFee); event NewRoutes(uint[] newRoutes); event NewCourier(address newCourier); event NewGuardian(address newGuardian); constructor() {} function initialize(address _courier, address _guardian, address _bridgeToken, uint _fee, uint[] memory newRoutes) public { require( courier == address(0) && guardian == address(0) && bridgeToken == address(0) && fee == 0 && routes.length == 0 , "PieBridge may only be initialized once" ); admin = msg.sender; require(_courier != address(0), "PieBridge: courier address is 0"); _setCourier(_courier); require(_guardian != address(0), "PieBridge: guardian address is 0"); _setGuardian(_guardian); require(_bridgeToken != address(0), "PieBridge: bridgeToken address is 0"); bridgeToken = _bridgeToken; _setFee(_fee); _setRoutes(newRoutes); } function cross(uint chainId, address to, uint amount) public returns (bool) { require(amount > fee, "PieBridge: amount must be more than fee"); require(to != address(0), "PieBridge: to address is 0"); require(checkRoute(chainId), "PieBridge: chainId is not support"); doTransferIn(msg.sender, bridgeToken, amount); doTransferOut(bridgeToken, courier, fee); crossNonce[chainId]++; emit Cross(msg.sender, to, amount - fee, chainId, crossNonce[chainId]); return true; } function deliver(uint fromChainId, address to, uint amount, uint nonce) public returns (bool) { require(msg.sender == courier, 'PieBridge: Only courier can deliver tokens'); require(amount > 0, "PieBridge: amount must be positive"); require(to != address(0), "PieBridge: to address is 0"); require(!deliverNonces[fromChainId][nonce], "PieBridge: bad nonce"); doTransferOut(bridgeToken, to, amount); deliverNonces[fromChainId][nonce] = true; emit Deliver(fromChainId, to, amount, nonce); return true; } function _setCourier(address newCourier) public returns (bool) { // Check caller = admin require(msg.sender == admin, 'PieBridge: Only admin can set courier'); // Store courier with value newCourier courier = newCourier; emit NewCourier(courier); return true; } function _setGuardian(address newGuadrdian) public returns (bool) { // Check caller = admin require(msg.sender == admin, 'PieBridge: Only admin can set guardian'); // Store guardian with value guardian guardian = newGuadrdian; emit NewGuardian(guardian); return true; } function unsetCourier() public returns (bool) { // Check caller = guardian require(msg.sender == guardian, 'PieBridge: Only guardian can unset courier'); // Store courier with value address(0) courier = address(0); emit NewCourier(courier); return true; } function _setFee(uint newFee) public returns (bool) { // Check caller = admin require(msg.sender == admin, 'PieBridge: Only admin can set fee'); // Store fee with value newFee fee = newFee; emit NewFee(newFee); return true; } function getRoutes() public view returns (uint[] memory) { return routes; } function _setRoutes(uint[] memory newRoutes) public { // Check caller = admin require(msg.sender == admin, 'PieBridge: Only admin can set routes'); routes = newRoutes; emit NewRoutes(routes); } function checkRoute(uint toChainId) public view returns (bool) { for(uint i = 0; i < routes.length; i++) { if (routes[i] == toChainId) { return true; } } return false; } function doTransferOut(address token, address to, uint amount) internal { IERC20 ERC20Interface = IERC20(token); ERC20Interface.safeTransfer(to, amount); } function doTransferIn(address from, address token, uint amount) internal { IERC20 ERC20Interface = IERC20(token); ERC20Interface.safeTransferFrom(from, address(this), amount); } }
Check caller = guardian Store courier with value address(0)
function unsetCourier() public returns (bool) { require(msg.sender == guardian, 'PieBridge: Only guardian can unset courier'); courier = address(0); emit NewCourier(courier); return true; }
6,425,957
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event Failure(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS } /** * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ADMIN_OWNER_CHECK, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } /** * @dev Add two numbers together, overflow will lead to revert. */ function srcAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } /** * @dev Integer subtraction of two numbers, overflow will lead to revert. */ function srcSub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } /** * @dev Multiplies two numbers, overflow will lead to revert. */ function srcMul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } /** * @dev Integer division of two numbers, truncating the quotient. */ function srcDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y > 0, "ds-math-div-overflow"); z = x / y; } /** * @dev x to the power of y power(base, exponent) */ function pow(uint256 base, uint256 exponent) internal pure returns (uint256) { if (exponent == 0) { return 1; } else if (exponent == 1) { return base; } else if (base == 0 && exponent != 0) { return 0; } else { uint256 z = base; for (uint256 i = 1; i < exponent; i++) z = srcMul(z, base); return z; } } } contract Exponential is CarefulMath { // TODO: We may wish to put the result of 10**18 here instead of the expression. // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; // See TODO on expScale uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; uint256 constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (Error.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (Error.NO_ERROR, Exp({ mantissa: scaledMantissa })); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (Error.NO_ERROR, Exp({ mantissa: descaledMantissa })); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint256 doubleScaledProductWithHalfScale) = add(halfExpScale, doubleScaledProduct); if (err1 != Error.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (Error err2, uint256 product) = div(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / 10**18; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } interface ExchangeRateModel { function scale() external view returns (uint256); function token() external view returns (address); function getExchangeRate() external view returns (uint256); function getMaxSwingRate(uint256 interval) external view returns (uint256); function getFixedInterestRate(uint256 interval) external view returns (uint256); function getFixedExchangeRate(uint256 interval) external view returns (uint256); } interface IERC20 { function decimals() external view returns (uint8); } interface IAggregator { function ref() external view returns (address); function getReferenceData(string memory _base, string memory _quote) external view returns (uint256, uint256, uint256); } interface IPriceModel { function getAssetPrice(address _asset) external view returns (uint256); } contract PriceOracleBand is Exponential { // Flag for whether or not contract is paused. bool public paused; // Approximately 1 hour: 60 seconds/minute * 60 minutes/hour * 1 block/15 seconds. uint256 public constant numBlocksPerPeriod = 240; uint256 public constant maxSwingMantissa = (5 * 10**15); // 0.005 uint256 public constant MINIMUM_SWING = 10**15; uint256 public constant MAXIMUM_SWING = 10**17; uint256 public constant SECONDS_PER_WEEK = 604800; /** * @dev An administrator who can set the pending anchor value for assets. * Set in the constructor. */ address public anchorAdmin; /** * @dev Pending anchor administrator for this contract. */ address public pendingAnchorAdmin; /** * @dev Address of the price poster. * Set in the constructor. */ address public poster; /** * @dev The maximum allowed percentage difference between a new price and the anchor's price * Set only in the constructor */ Exp public maxSwing; /** * @dev The maximum allowed percentage difference for all assets between a new price and the anchor's price */ mapping(address => Exp) public maxSwings; /** * @dev Mapping of asset addresses to exchange rate information. * Dynamic changes in asset prices based on exchange rates. * map: assetAddress -> ExchangeRateInfo */ struct ExchangeRateInfo { address exchangeRateModel; // Address of exchange rate model contract uint256 exchangeRate; // Exchange rate between token and wrapped token uint256 maxSwingRate; // Maximum changing ratio of the exchange rate uint256 maxSwingDuration; // Duration of maximum changing ratio of the exchange rate } mapping(address => ExchangeRateInfo) public exchangeRates; /** * @dev Mapping of asset addresses to asset addresses. Stable coin can share a price. * * map: assetAddress -> Reader */ struct Reader { address asset; // Asset to read price int256 decimalsDifference; // Standard decimal is 18, so this is equal to the decimal of `asset` - 18. } mapping(address => Reader) public readers; /** * @dev Mapping of asset addresses and their corresponding price in terms of Eth-Wei * which is simply equal to AssetWeiPrice * 10e18. For instance, if OMG token was * worth 5x Eth then the price for OMG would be 5*10e18 or Exp({mantissa: 5000000000000000000}). * map: assetAddress -> Exp */ mapping(address => Exp) public _assetPrices; /** * @dev The address of the aggregator who gets the asset price. */ IAggregator public aggregator; uint256 public constant AGGREGATOR_DECIMALS = 18; /** * @dev Mapping of asset addresses to symbol. */ mapping(address => string) public symbols; /** * @dev Mapping of asset addresses to priceModel. */ mapping(address => IPriceModel) public priceModels; constructor(address _poster, uint256 _maxSwing) public { anchorAdmin = msg.sender; poster = _poster; _setMaxSwing(_maxSwing); } /** * @notice Do not pay into PriceOracle. */ receive() external payable { revert(); } enum OracleError { NO_ERROR, UNAUTHORIZED, FAILED_TO_SET_PRICE } enum OracleFailureInfo { ACCEPT_ANCHOR_ADMIN_PENDING_ANCHOR_ADMIN_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ANCHOR_ADMIN_OWNER_CHECK, SET_PENDING_ANCHOR_PERMISSION_CHECK, SET_PRICE_CALCULATE_SWING, SET_PRICE_CAP_TO_MAX, SET_PRICE_MAX_SWING_CHECK, SET_PRICE_NO_ANCHOR_PRICE_OR_INITIAL_PRICE_ZERO, SET_PRICE_PERMISSION_CHECK, SET_PRICE_ZERO_PRICE, SET_PRICES_PARAM_VALIDATION, SET_PRICE_IS_READER_ASSET } /** * @dev `msgSender` is msg.sender; `error` corresponds to enum OracleError; * `info` corresponds to enum OracleFailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event OracleFailure( address msgSender, address asset, uint256 error, uint256 info, uint256 detail ); /** * @dev Use this when reporting a known error from the price oracle or a non-upgradeable collaborator * Using Oracle in name because we already inherit a `fail` function from ErrorReporter.sol * via Exponential.sol */ function failOracle( address _asset, OracleError _err, OracleFailureInfo _info ) internal returns (uint256) { emit OracleFailure(msg.sender, _asset, uint256(_err), uint256(_info), 0); return uint256(_err); } /** * @dev Use this to report an error when set asset price. * Give the `error` corresponds to enum Error as `_details`. */ function failOracleWithDetails( address _asset, OracleError _err, OracleFailureInfo _info, uint256 _details ) internal returns (uint256) { emit OracleFailure( msg.sender, _asset, uint256(_err), uint256(_info), _details ); return uint256(_err); } struct Anchor { // Floor(block.number / numBlocksPerPeriod) + 1 uint256 period; // Price in ETH, scaled by 10**18 uint256 priceMantissa; } /** * @dev Anchors by asset. */ mapping(address => Anchor) public anchors; /** * @dev Pending anchor prices by asset. */ mapping(address => uint256) public pendingAnchors; /** * @dev Emitted when a pending anchor is set. * @param asset Asset for which to set a pending anchor. * @param oldScaledPrice If an unused pending anchor was present, its value; otherwise 0. * @param newScaledPrice The new scaled pending anchor price. */ event NewPendingAnchor( address anchorAdmin, address asset, uint256 oldScaledPrice, uint256 newScaledPrice ); /** * @notice Provides ability to override the anchor price for an asset. * @dev Admin function to set the anchor price for an asset. * @param _asset Asset for which to override the anchor price. * @param _newScaledPrice New anchor price. * @return uint 0=success, otherwise a failure (see enum OracleError for details). */ function _setPendingAnchor(address _asset, uint256 _newScaledPrice) external returns (uint256) { // Check caller = anchorAdmin. // Note: Deliberately not allowing admin. They can just change anchorAdmin if desired. if (msg.sender != anchorAdmin) { return failOracle( _asset, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PENDING_ANCHOR_PERMISSION_CHECK ); } uint256 _oldScaledPrice = pendingAnchors[_asset]; pendingAnchors[_asset] = _newScaledPrice; emit NewPendingAnchor( msg.sender, _asset, _oldScaledPrice, _newScaledPrice ); return uint256(OracleError.NO_ERROR); } /** * @dev Emitted for all exchangeRates changes. */ event SetExchangeRate( address asset, address exchangeRateModel, uint256 exchangeRate, uint256 maxSwingRate, uint256 maxSwingDuration ); event SetMaxSwingRate( address asset, uint256 oldMaxSwingRate, uint256 newMaxSwingRate, uint256 maxSwingDuration ); /** * @dev Emitted for all readers changes. */ event ReaderPosted( address asset, address oldReader, address newReader, int256 decimalsDifference ); /** * @dev Emitted for max swing changes. */ event SetMaxSwing(uint256 maxSwing); /** * @dev Emitted for max swing changes. */ event SetMaxSwingForAsset(address asset, uint256 maxSwing); /** * @dev Emitted for aggregator changes. */ event SetAggregator(IAggregator oldAggregator, IAggregator aggregator); /** * @dev Emitted for symbol changes. */ event SetAssetSymbol(address asset, string symbol); /** * @dev Emitted for priceModel changes. */ event SetAssetPriceModel(address asset, IPriceModel priceModel); /** * @dev Emitted for all price changes. */ event PricePosted( address asset, uint256 previousPriceMantissa, uint256 requestedPriceMantissa, uint256 newPriceMantissa ); /** * @dev Emitted if this contract successfully posts a capped-to-max price. */ event CappedPricePosted( address asset, uint256 requestedPriceMantissa, uint256 anchorPriceMantissa, uint256 cappedPriceMantissa ); /** * @dev Emitted when admin either pauses or resumes the contract; `newState` is the resulting state. */ event SetPaused(bool newState); /** * @dev Emitted when `pendingAnchorAdmin` is changed. */ event NewPendingAnchorAdmin( address oldPendingAnchorAdmin, address newPendingAnchorAdmin ); /** * @dev Emitted when `pendingAnchorAdmin` is accepted, which means anchor admin is updated. */ event NewAnchorAdmin(address oldAnchorAdmin, address newAnchorAdmin); /** * @dev Emitted when `poster` is changed. */ event NewPoster(address oldPoster, address newPoster); /** * @notice Set `paused` to the specified state. * @dev Admin function to pause or resume the contract. * @param _requestedState Value to assign to `paused`. * @return uint 0=success, otherwise a failure. */ function _setPaused(bool _requestedState) external returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } paused = _requestedState; emit SetPaused(_requestedState); return uint256(Error.NO_ERROR); } /** * @notice Begins to transfer the right of anchor admin. * The `_newPendingAnchorAdmin` must call `_acceptAnchorAdmin` to finalize the transfer. * @dev Admin function to change the anchor admin. * The `_newPendingAnchorAdmin` must call `_acceptAnchorAdmin` to finalize the transfer. * @param _newPendingAnchorAdmin New pending anchor admin. * @return uint 0=success, otherwise a failure. */ function _setPendingAnchorAdmin(address _newPendingAnchorAdmin) external returns (uint256) { // Check caller = anchorAdmin. if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PENDING_ANCHOR_ADMIN_OWNER_CHECK ); } // Save current value, if any, for inclusion in log. address _oldPendingAnchorAdmin = pendingAnchorAdmin; // Store pendingAdmin = newPendingAdmin. pendingAnchorAdmin = _newPendingAnchorAdmin; emit NewPendingAnchorAdmin( _oldPendingAnchorAdmin, _newPendingAnchorAdmin ); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of anchor admin rights. `msg.sender` must be `pendingAnchorAdmin`. * @dev Admin function for pending anchor admin to accept role and update anchor admin` * @return uint 0=success, otherwise a failure` */ function _acceptAnchorAdmin() external returns (uint256) { // Check caller = pendingAnchorAdmin. // `msg.sender` can't be zero. if (msg.sender != pendingAnchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo .ACCEPT_ANCHOR_ADMIN_PENDING_ANCHOR_ADMIN_CHECK ); } // Save current value for inclusion in log. address _oldAnchorAdmin = anchorAdmin; // Store admin = pendingAnchorAdmin. anchorAdmin = pendingAnchorAdmin; // Clear the pending value. pendingAnchorAdmin = address(0); emit NewAnchorAdmin(_oldAnchorAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Set new poster. * @dev Admin function to change of poster. * @param _newPoster New poster. * @return uint 0=success, otherwise a failure. * * TODO: Should we add a second arg to verify, like a checksum of `newAnchorAdmin` address? */ function _setPoster(address _newPoster) external returns (uint256) { assert(poster != _newPoster); // Check caller = anchorAdmin. if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PENDING_ANCHOR_ADMIN_OWNER_CHECK ); } // Save current value, if any, for inclusion in log. address _oldPoster = poster; // Store poster = newPoster. poster = _newPoster; emit NewPoster(_oldPoster, _newPoster); return uint256(Error.NO_ERROR); } /** * @notice Set new exchange rate model. * @dev Function to set exchangeRateModel for an asset. * @param _asset Asset to set the new `_exchangeRateModel`. * @param _exchangeRateModel New `_exchangeRateModel` cnotract address, * if the `_exchangeRateModel` is address(0), revert to cancle. * @param _maxSwingDuration A value greater than zero and less than the seconds of a week. * @return uint 0=success, otherwise a failure (see enum OracleError for details). */ function setExchangeRate( address _asset, address _exchangeRateModel, uint256 _maxSwingDuration ) external returns (uint256) { // Check caller = anchorAdmin. if (msg.sender != anchorAdmin) { return failOracle( _asset, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK ); } require( _exchangeRateModel != address(0), "setExchangeRate: exchangeRateModel cannot be a zero address." ); require( _maxSwingDuration > 0 && _maxSwingDuration <= SECONDS_PER_WEEK, "setExchangeRate: maxSwingDuration cannot be zero, less than 604800 (seconds per week)." ); uint256 _currentExchangeRate = ExchangeRateModel(_exchangeRateModel).getExchangeRate(); require( _currentExchangeRate > 0, "setExchangeRate: currentExchangeRate not zero." ); uint256 _maxSwingRate = ExchangeRateModel(_exchangeRateModel).getMaxSwingRate( _maxSwingDuration ); require( _maxSwingRate > 0 && _maxSwingRate <= ExchangeRateModel(_exchangeRateModel).getMaxSwingRate( SECONDS_PER_WEEK ), "setExchangeRate: maxSwingRate cannot be zero, less than 604800 (seconds per week)." ); exchangeRates[_asset].exchangeRateModel = _exchangeRateModel; exchangeRates[_asset].exchangeRate = _currentExchangeRate; exchangeRates[_asset].maxSwingRate = _maxSwingRate; exchangeRates[_asset].maxSwingDuration = _maxSwingDuration; emit SetExchangeRate( _asset, _exchangeRateModel, _currentExchangeRate, _maxSwingRate, _maxSwingDuration ); return uint256(OracleError.NO_ERROR); } /** * @notice Set a new `maxSwingRate`. * @dev Function to set exchange rate `maxSwingRate` for an asset. * @param _asset Asset for which to set the exchange rate `maxSwingRate`. * @param _maxSwingDuration Interval time. * @return uint 0=success, otherwise a failure (see enum OracleError for details) */ function setMaxSwingRate(address _asset, uint256 _maxSwingDuration) external returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( _asset, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK ); } require( _maxSwingDuration > 0 && _maxSwingDuration <= SECONDS_PER_WEEK, "setMaxSwingRate: maxSwingDuration cannot be zero, less than 604800 (seconds per week)." ); ExchangeRateModel _exchangeRateModel = ExchangeRateModel(exchangeRates[_asset].exchangeRateModel); uint256 _newMaxSwingRate = _exchangeRateModel.getMaxSwingRate(_maxSwingDuration); uint256 _oldMaxSwingRate = exchangeRates[_asset].maxSwingRate; require( _oldMaxSwingRate != _newMaxSwingRate, "setMaxSwingRate: the same max swing rate." ); require( _newMaxSwingRate > 0 && _newMaxSwingRate <= _exchangeRateModel.getMaxSwingRate(SECONDS_PER_WEEK), "setMaxSwingRate: maxSwingRate cannot be zero, less than 31536000 (seconds per week)." ); exchangeRates[_asset].maxSwingRate = _newMaxSwingRate; exchangeRates[_asset].maxSwingDuration = _maxSwingDuration; emit SetMaxSwingRate( _asset, _oldMaxSwingRate, _newMaxSwingRate, _maxSwingDuration ); return uint256(OracleError.NO_ERROR); } /** * @notice Entry point for updating prices. * @dev Set reader for an asset. * @param _asset Asset for which to set the reader. * @param _readAsset Reader address, if the reader is address(0), cancel the reader. * @return uint 0=success, otherwise a failure (see enum OracleError for details). */ function setReaders(address _asset, address _readAsset) external returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( _asset, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK ); } address _oldReadAsset = readers[_asset].asset; // require(_readAsset != _oldReadAsset, "setReaders: Old and new values cannot be the same."); require( _readAsset != _asset, "setReaders: asset and readAsset cannot be the same." ); readers[_asset].asset = _readAsset; if (_readAsset == address(0)) readers[_asset].decimalsDifference = 0; else readers[_asset].decimalsDifference = int256( IERC20(_asset).decimals() - IERC20(_readAsset).decimals() ); emit ReaderPosted( _asset, _oldReadAsset, _readAsset, readers[_asset].decimalsDifference ); return uint256(OracleError.NO_ERROR); } /** * @notice Set `maxSwing` to the specified value. * @dev Admin function to change of max swing. * @param _maxSwing Value to assign to `maxSwing`. * @return uint 0=success, otherwise a failure. */ function _setMaxSwing(uint256 _maxSwing) public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } uint256 _oldMaxSwing = maxSwing.mantissa; require( _maxSwing != _oldMaxSwing, "_setMaxSwing: Old and new values cannot be the same." ); require( _maxSwing >= MINIMUM_SWING && _maxSwing <= MAXIMUM_SWING, "_setMaxSwing: 0.1% <= _maxSwing <= 10%." ); maxSwing = Exp({ mantissa: _maxSwing }); emit SetMaxSwing(_maxSwing); return uint256(Error.NO_ERROR); } /** * @notice Set `maxSwing` for asset to the specified value. * @dev Admin function to change of max swing. * @param _asset Asset for which to set the `maxSwing`. * @param _maxSwing Value to assign to `maxSwing`. * @return uint 0=success, otherwise a failure. */ function _setMaxSwingForAsset(address _asset, uint256 _maxSwing) public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } uint256 _oldMaxSwing = maxSwings[_asset].mantissa; require( _maxSwing != _oldMaxSwing, "_setMaxSwingForAsset: Old and new values cannot be the same." ); require( _maxSwing >= MINIMUM_SWING && _maxSwing <= MAXIMUM_SWING, "_setMaxSwingForAsset: 0.1% <= _maxSwing <= 10%." ); maxSwings[_asset] = Exp({ mantissa: _maxSwing }); emit SetMaxSwingForAsset(_asset, _maxSwing); return uint256(Error.NO_ERROR); } function _setMaxSwingForAssetBatch( address[] calldata _assets, uint256[] calldata _maxSwings ) external { require( _assets.length == _maxSwings.length, "_setMaxSwingForAssetBatch: assets & maxSwings must match the current length." ); for (uint256 i = 0; i < _assets.length; i++) _setMaxSwingForAsset(_assets[i], _maxSwings[i]); } /** * @notice Set `aggregator` to the specified address. * @dev Admin function to change of aggregator. * @param _aggregator Address to assign to `aggregator`. * @return uint 0=success, otherwise a failure. */ function _setAggregator(IAggregator _aggregator) public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } require( _aggregator.ref() != address(0), "_setAggregator: This is not the aggregator contract!" ); IAggregator _oldAggregator = aggregator; require( _aggregator != _oldAggregator, "_setAggregator: Old and new address cannot be the same." ); aggregator = _aggregator; emit SetAggregator(_oldAggregator, _aggregator); return uint256(Error.NO_ERROR); } /** * @notice Set the `aggregator` to disabled. * @dev Admin function to disable of aggregator. * @return uint 0=success, otherwise a failure. */ function _disableAggregator() public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } IAggregator _oldAggregator = aggregator; aggregator = IAggregator(0); emit SetAggregator(_oldAggregator, IAggregator(0)); return uint256(Error.NO_ERROR); } /** * @notice Set `symbol` for asset to the specified string. * @dev Admin function to change of symbol. * @param _asset Asset for which to set the `symbol`. * @param _symbol String to assign to `symbol`. * @return uint 0=success, otherwise a failure. */ function _setAssetSymbol(address _asset, string memory _symbol) public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } symbols[_asset] = _symbol; emit SetAssetSymbol(_asset, _symbol); return uint256(Error.NO_ERROR); } /** * @notice Set `priceModels` for asset to the specified address. * @dev Admin function to change of priceModels. * @param _asset Asset for which to set the `priceModels`. * @param _priceModel Address to assign to `priceModels`. * @return uint 0=success, otherwise a failure.SetAssetPriceModel */ function _setAssetPriceModel(address _asset, IPriceModel _priceModel) public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } require( _priceModel.getAssetPrice(_asset) >= 0, "_setAssetPriceModel: This is not the priceModel contract!" ); priceModels[_asset] = _priceModel; emit SetAssetPriceModel(_asset, _priceModel); return uint256(Error.NO_ERROR); } function _setAssetPriceModelBatch( address[] calldata _assets, IPriceModel[] calldata _priceModels ) external { require( _assets.length == _priceModels.length, "_setAssetPriceModelBatch: assets & _priceModels must match the current length." ); for (uint256 i = 0; i < _assets.length; i++) _setAssetPriceModel(_assets[i], _priceModels[i]); } /** * @notice Set the `priceModels` to disabled. * @dev Admin function to disable of priceModels. * @return uint 0=success, otherwise a failure. */ function _disablePriceModel(address _asset) public returns (uint256) { // Check caller = anchorAdmin if (msg.sender != anchorAdmin) { return failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PAUSED_OWNER_CHECK ); } priceModels[_asset] = IPriceModel(0); emit SetAssetPriceModel(_asset, IPriceModel(0)); return uint256(Error.NO_ERROR); } /** * @notice Asset prices are provided by aggregator. * @dev Get price of `asset` from aggregator. * @param _asset Asset for which to get the price. * @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or under unexpected case. */ function _getAssetAggregatorPrice(address _asset) internal view returns (uint256) { if (aggregator == IAggregator(0)) return 0; string memory _assetSymbol = symbols[_asset]; if (bytes(_assetSymbol).length == 0) return 0; (uint256 _aggregatorPrice, ,) = aggregator.getReferenceData(_assetSymbol, "USD"); return srcMul( _aggregatorPrice, 10 ** (srcSub(36, srcAdd(uint256(IERC20(_asset).decimals()), AGGREGATOR_DECIMALS))) ); } function getAssetAggregatorPrice(address _asset) external view returns (uint256) { return _getAssetAggregatorPrice(_asset); } /** * @notice Asset prices are provided by priceModel. * @dev Get price of `asset` from priceModel. * @param _asset Asset for which to get the price. * @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or under unexpected case. */ function _getPriceModelPrice(address _asset) internal view returns (uint256) { IPriceModel _priceModel = priceModels[_asset]; if (_priceModel == IPriceModel(0)) return 0; return _priceModel.getAssetPrice(_asset); } function getPriceModelPrice(address _asset) external view returns (uint256) { return _getPriceModelPrice(_asset); } /** * @notice Asset prices are provided by chain link or a reader. * @dev Get price of `asset`. * @param _asset Asset for which to get the price. * @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or under unexpected case. */ function _getAssetPrice(address _asset) internal view returns (uint256) { uint256 _assetPrice = _getAssetAggregatorPrice(_asset); if (_assetPrice == 0) _assetPrice = _getPriceModelPrice(_asset); if (_assetPrice == 0) return _getReaderPrice(_asset); return _assetPrice; } function getAssetPrice(address _asset) external view returns (uint256) { return _getAssetPrice(_asset); } /** * @notice This is a basic function to read price, although this is a public function, * It is not recommended, the recommended function is `assetPrices(asset)`. * If `asset` does not has a reader to reader price, then read price from original * structure `_assetPrices`; * If `asset` has a reader to read price, first gets the price of reader, then * `readerPrice * 10 ** |(18-assetDecimals)|` * @dev Get price of `asset`. * @param _asset Asset for which to get the price. * @return Uint mantissa of asset price (scaled by 1e18) or zero if unset. */ function _getReaderPrice(address _asset) internal view returns (uint256) { Reader storage reader = readers[_asset]; if (reader.asset == address(0)) return _assetPrices[_asset].mantissa; uint256 readerPrice = _assetPrices[reader.asset].mantissa; if (reader.decimalsDifference < 0) return srcMul( readerPrice, pow(10, uint256(0 - reader.decimalsDifference)) ); return srcDiv(readerPrice, pow(10, uint256(reader.decimalsDifference))); } function getReaderPrice(address _asset) external view returns (uint256) { return _getReaderPrice(_asset); } /** * @notice Retrieves price of an asset. * @dev Get price for an asset. * @param _asset Asset for which to get the price. * @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or contract paused. */ function assetPrices(address _asset) internal view returns (uint256) { // Note: zero is treated by the xSwap as an invalid // price and will cease operations with that asset // when zero. // // We get the price as: // // 1. If the contract is paused, return 0. // 2. If the asset has an exchange rate model, the asset price is calculated based on the exchange rate. // 3. Return price in `_assetPrices`, which may be zero. if (paused) { return 0; } else { uint256 _assetPrice = _getAssetPrice(_asset); ExchangeRateInfo storage _exchangeRateInfo = exchangeRates[_asset]; if (_exchangeRateInfo.exchangeRateModel != address(0)) { uint256 _scale = ExchangeRateModel(_exchangeRateInfo.exchangeRateModel) .scale(); uint256 _currentExchangeRate = ExchangeRateModel(_exchangeRateInfo.exchangeRateModel) .getExchangeRate(); uint256 _currentChangeRate; Error _err; (_err, _currentChangeRate) = mul(_currentExchangeRate, _scale); if (_err != Error.NO_ERROR) return 0; _currentChangeRate = _currentChangeRate / _exchangeRateInfo.exchangeRate; // require(_currentExchangeRate >= _exchangeRateInfo.exchangeRate && _currentChangeRate <= _exchangeRateInfo.maxSwingRate, "assetPrices: Abnormal exchange rate."); if ( _currentExchangeRate < _exchangeRateInfo.exchangeRate || _currentChangeRate > _exchangeRateInfo.maxSwingRate ) return 0; uint256 _price; (_err, _price) = mul(_assetPrice, _currentExchangeRate); if (_err != Error.NO_ERROR) return 0; return _price / _scale; } else { return _assetPrice; } } } /** * @notice Retrieves price of an asset. * @dev Get price for an asset. * @param _asset Asset for which to get the price. * @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or contract paused. */ function getUnderlyingPrice(address _asset) external view returns (uint256) { return assetPrices(_asset); } /** * @dev Get exchange rate info of an asset in the time of `interval`. * @param _asset Asset for which to get the exchange rate info. * @param _interval Time to get accmulator interest rate. * @return Asset price, exchange rate model address, the token that is using this exchange rate model, * exchange rate model contract address, * the token that is using this exchange rate model, * scale between token and wrapped token, * exchange rate between token and wrapped token, * After the time of `_interval`, get the accmulator interest rate. */ function getExchangeRateInfo(address _asset, uint256 _interval) external view returns ( uint256, address, address, uint256, uint256, uint256 ) { if (exchangeRates[_asset].exchangeRateModel == address(0)) return (_getReaderPrice(_asset), address(0), address(0), 0, 0, 0); return ( _getReaderPrice(_asset), exchangeRates[_asset].exchangeRateModel, ExchangeRateModel(exchangeRates[_asset].exchangeRateModel).token(), ExchangeRateModel(exchangeRates[_asset].exchangeRateModel).scale(), ExchangeRateModel(exchangeRates[_asset].exchangeRateModel) .getExchangeRate(), ExchangeRateModel(exchangeRates[_asset].exchangeRateModel) .getFixedInterestRate(_interval) ); } struct SetPriceLocalVars { Exp price; Exp swing; Exp maxSwing; Exp anchorPrice; uint256 anchorPeriod; uint256 currentPeriod; bool priceCapped; uint256 cappingAnchorPriceMantissa; uint256 pendingAnchorMantissa; } /** * @notice Entry point for updating prices. * 1) If admin has set a `readerPrice` for this asset, then poster can not use this function. * 2) Standard stablecoin has 18 deicmals, and its price should be 1e18, * so when the poster set a new price for a token, * `requestedPriceMantissa` = actualPrice * 10 ** (18-tokenDecimals), * actualPrice is scaled by 10**18. * @dev Set price for an asset. * @param _asset Asset for which to set the price. * @param _requestedPriceMantissa Requested new price, scaled by 10**18. * @return Uint 0=success, otherwise a failure (see enum OracleError for details). */ function setPrice(address _asset, uint256 _requestedPriceMantissa) external returns (uint256) { // Fail when msg.sender is not poster if (msg.sender != poster) { return failOracle( _asset, OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK ); } return setPriceInternal(_asset, _requestedPriceMantissa); } function setPriceInternal(address _asset, uint256 _requestedPriceMantissa) internal returns (uint256) { // re-used for intermediate errors Error _err; SetPriceLocalVars memory _localVars; // We add 1 for currentPeriod so that it can never be zero and there's no ambiguity about an unset value. // (It can be a problem in tests with low block numbers.) _localVars.currentPeriod = (block.number / numBlocksPerPeriod) + 1; _localVars.pendingAnchorMantissa = pendingAnchors[_asset]; _localVars.price = Exp({ mantissa: _requestedPriceMantissa }); if (exchangeRates[_asset].exchangeRateModel != address(0)) { uint256 _currentExchangeRate = ExchangeRateModel(exchangeRates[_asset].exchangeRateModel) .getExchangeRate(); uint256 _scale = ExchangeRateModel(exchangeRates[_asset].exchangeRateModel) .scale(); uint256 _currentChangeRate; (_err, _currentChangeRate) = mul(_currentExchangeRate, _scale); assert(_err == Error.NO_ERROR); _currentChangeRate = _currentChangeRate / exchangeRates[_asset].exchangeRate; require( _currentExchangeRate >= exchangeRates[_asset].exchangeRate && _currentChangeRate <= exchangeRates[_asset].maxSwingRate, "setPriceInternal: Abnormal exchange rate." ); exchangeRates[_asset].exchangeRate = _currentExchangeRate; } if (readers[_asset].asset != address(0)) { return failOracle( _asset, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICE_IS_READER_ASSET ); } _localVars.maxSwing = maxSwings[_asset].mantissa == 0 ? maxSwing : maxSwings[_asset]; if (_localVars.pendingAnchorMantissa != 0) { // let's explicitly set to 0 rather than relying on default of declaration _localVars.anchorPeriod = 0; _localVars.anchorPrice = Exp({ mantissa: _localVars.pendingAnchorMantissa }); // Verify movement is within max swing of pending anchor (currently: 10%) (_err, _localVars.swing) = calculateSwing( _localVars.anchorPrice, _localVars.price ); if (_err != Error.NO_ERROR) { return failOracleWithDetails( _asset, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICE_CALCULATE_SWING, uint256(_err) ); } // Fail when swing > maxSwing // if (greaterThanExp(_localVars.swing, maxSwing)) { if (greaterThanExp(_localVars.swing, _localVars.maxSwing)) { return failOracleWithDetails( _asset, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICE_MAX_SWING_CHECK, _localVars.swing.mantissa ); } } else { _localVars.anchorPeriod = anchors[_asset].period; _localVars.anchorPrice = Exp({ mantissa: anchors[_asset].priceMantissa }); if (_localVars.anchorPeriod != 0) { // (_err, _localVars.priceCapped, _localVars.price) = capToMax(_localVars.anchorPrice, _localVars.price); (_err, _localVars.priceCapped, _localVars.price) = capToMax( _localVars.anchorPrice, _localVars.price, _localVars.maxSwing ); if (_err != Error.NO_ERROR) { return failOracleWithDetails( _asset, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICE_CAP_TO_MAX, uint256(_err) ); } if (_localVars.priceCapped) { // save for use in log _localVars.cappingAnchorPriceMantissa = _localVars .anchorPrice .mantissa; } } else { // Setting first price. Accept as is (already assigned above from _requestedPriceMantissa) and use as anchor _localVars.anchorPrice = Exp({ mantissa: _requestedPriceMantissa }); } } // Fail if anchorPrice or price is zero. // zero anchor represents an unexpected situation likely due to a problem in this contract // zero price is more likely as the result of bad input from the caller of this function if (isZeroExp(_localVars.anchorPrice)) { // If we get here price could also be zero, but it does not seem worthwhile to distinguish the 3rd case return failOracle( _asset, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo .SET_PRICE_NO_ANCHOR_PRICE_OR_INITIAL_PRICE_ZERO ); } if (isZeroExp(_localVars.price)) { return failOracle( _asset, OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICE_ZERO_PRICE ); } // BEGIN SIDE EFFECTS // Set pendingAnchor = Nothing // Pending anchor is only used once. if (pendingAnchors[_asset] != 0) { pendingAnchors[_asset] = 0; } // If currentPeriod > anchorPeriod: // Set anchors[_asset] = (currentPeriod, price) // The new anchor is if we're in a new period or we had a pending anchor, then we become the new anchor if (_localVars.currentPeriod > _localVars.anchorPeriod) { anchors[_asset] = Anchor({ period: _localVars.currentPeriod, priceMantissa: _localVars.price.mantissa }); } uint256 _previousPrice = _assetPrices[_asset].mantissa; setPriceStorageInternal(_asset, _localVars.price.mantissa); emit PricePosted( _asset, _previousPrice, _requestedPriceMantissa, _localVars.price.mantissa ); if (_localVars.priceCapped) { // We have set a capped price. Log it so we can detect the situation and investigate. emit CappedPricePosted( _asset, _requestedPriceMantissa, _localVars.cappingAnchorPriceMantissa, _localVars.price.mantissa ); } return uint256(OracleError.NO_ERROR); } // As a function to allow harness overrides function setPriceStorageInternal(address _asset, uint256 _priceMantissa) internal { _assetPrices[_asset] = Exp({ mantissa: _priceMantissa }); } // abs(price - anchorPrice) / anchorPrice function calculateSwing(Exp memory _anchorPrice, Exp memory _price) internal pure returns (Error, Exp memory) { Exp memory numerator; Error err; if (greaterThanExp(_anchorPrice, _price)) { (err, numerator) = subExp(_anchorPrice, _price); // can't underflow assert(err == Error.NO_ERROR); } else { (err, numerator) = subExp(_price, _anchorPrice); // Given greaterThan check above, _price >= _anchorPrice so can't underflow. assert(err == Error.NO_ERROR); } return divExp(numerator, _anchorPrice); } // Base on the current anchor price, get the final valid price. function capToMax( Exp memory _anchorPrice, Exp memory _price, Exp memory _maxSwing ) internal pure returns ( Error, bool, Exp memory ) { Exp memory one = Exp({ mantissa: mantissaOne }); Exp memory onePlusMaxSwing; Exp memory oneMinusMaxSwing; Exp memory max; Exp memory min; // re-used for intermediate errors Error err; (err, onePlusMaxSwing) = addExp(one, _maxSwing); if (err != Error.NO_ERROR) { return (err, false, Exp({ mantissa: 0 })); } // max = _anchorPrice * (1 + _maxSwing) (err, max) = mulExp(_anchorPrice, onePlusMaxSwing); if (err != Error.NO_ERROR) { return (err, false, Exp({ mantissa: 0 })); } // If _price > _anchorPrice * (1 + _maxSwing) // Set _price = _anchorPrice * (1 + _maxSwing) if (greaterThanExp(_price, max)) { return (Error.NO_ERROR, true, max); } (err, oneMinusMaxSwing) = subExp(one, _maxSwing); if (err != Error.NO_ERROR) { return (err, false, Exp({ mantissa: 0 })); } // min = _anchorPrice * (1 - _maxSwing) (err, min) = mulExp(_anchorPrice, oneMinusMaxSwing); // We can't overflow here or we would have already overflowed above when calculating `max` assert(err == Error.NO_ERROR); // If _price < _anchorPrice * (1 - _maxSwing) // Set _price = _anchorPrice * (1 - _maxSwing) if (lessThanExp(_price, min)) { return (Error.NO_ERROR, true, min); } return (Error.NO_ERROR, false, _price); } /** * @notice Entry point for updating multiple prices. * @dev Set prices for a variable number of assets. * @param _assets A list of up to assets for which to set a price. * Notice: 0 < _assets.length == _requestedPriceMantissas.length * @param _requestedPriceMantissas Requested new prices for the assets, scaled by 10**18. * Notice: 0 < _assets.length == _requestedPriceMantissas.length * @return Uint values in same order as inputs. * For each: 0=success, otherwise a failure (see enum OracleError for details) */ function setPrices( address[] memory _assets, uint256[] memory _requestedPriceMantissas ) external returns (uint256[] memory) { uint256 numAssets = _assets.length; uint256 numPrices = _requestedPriceMantissas.length; uint256[] memory result; // Fail when msg.sender is not poster if (msg.sender != poster) { result = new uint256[](1); result[0] = failOracle( address(0), OracleError.UNAUTHORIZED, OracleFailureInfo.SET_PRICE_PERMISSION_CHECK ); return result; } if ((numAssets == 0) || (numPrices != numAssets)) { result = new uint256[](1); result[0] = failOracle( address(0), OracleError.FAILED_TO_SET_PRICE, OracleFailureInfo.SET_PRICES_PARAM_VALIDATION ); return result; } result = new uint256[](numAssets); for (uint256 i = 0; i < numAssets; i++) { result[i] = setPriceInternal(_assets[i], _requestedPriceMantissas[i]); } return result; } }
abs(price - anchorPrice) / anchorPrice can't underflow Given greaterThan check above, _price >= _anchorPrice so can't underflow.
function calculateSwing(Exp memory _anchorPrice, Exp memory _price) internal pure returns (Error, Exp memory) { Exp memory numerator; Error err; if (greaterThanExp(_anchorPrice, _price)) { (err, numerator) = subExp(_anchorPrice, _price); assert(err == Error.NO_ERROR); (err, numerator) = subExp(_price, _anchorPrice); assert(err == Error.NO_ERROR); } return divExp(numerator, _anchorPrice); }
5,468,129
./full_match/56/0x1C5C0E1B96E7ADDC14AED3688E547A6103A244d9/sources/project_/contracts/Router1.sol
Calculates and returns the total fees from the `fees` array. return The total fees as a uint256./
function getTotalFees() public view returns (uint256) { uint256 totalFees = 0; for (uint256 i = 0; i < fees.length; i++) { totalFees += fees[i]; } return totalFees; }
3,227,287
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; // interface IERC20 { function TOTALSUPPLY709() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF1000(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER912(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE378(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM696(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER249(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL928(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // abstract contract Context { function _MSGSENDER905() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA980() 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 OWNERSHIPTRANSFERRED618(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER905(); _owner = msgSender; emit OWNERSHIPTRANSFERRED618(address(0), msgSender); } function OWNER941() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER378() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER905(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP149() public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED618(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP687(address newOwner) public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED618(_owner, newOwner); _owner = newOwner; } } // library SafeMath { function ADD236(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB786(a, b, "SafeMath: subtraction overflow"); } function SUB786(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 MUL747(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 DIV140(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV140(a, b, "SafeMath: division by zero"); } function DIV140(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 MOD599(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD599(a, b, "SafeMath: modulo by zero"); } function MOD599(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // library Address { function ISCONTRACT863(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE275(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL887(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL887(target, data, "Address: low-level call failed"); } function FUNCTIONCALL887(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE192(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE672(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE192(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE192(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT863(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // contract 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_entered586 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered769 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered586; } modifier NONREENTRANT44() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered769, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered769; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered586; } } // library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER115(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFER912.selector, to, value)); } function SAFETRANSFERFROM287(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFERFROM696.selector, from, to, value)); } function SAFEAPPROVE190(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE643(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, value)); } function SAFEINCREASEALLOWANCE374(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE643(address(this), spender).ADD236(value); _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE80(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE643(address(this), spender).SUB786(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN516(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).FUNCTIONCALL887(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"); } } } // contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME654() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL381() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS442() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY709() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF1000(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER912(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER205(_MSGSENDER905(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE378(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE516(_MSGSENDER905(), spender, amount); return true; } function TRANSFERFROM696(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER205(sender, recipient, amount); _APPROVE516(sender, _MSGSENDER905(), _allowances[sender][_MSGSENDER905()].SUB786(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE9(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].ADD236(addedValue)); return true; } function DECREASEALLOWANCE999(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].SUB786(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER205(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER183(sender, recipient, amount); _balances[sender] = _balances[sender].SUB786(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD236(amount); emit TRANSFER249(sender, recipient, amount); } function _MINT985(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER183(address(0), account, amount); _totalSupply = _totalSupply.ADD236(amount); _balances[account] = _balances[account].ADD236(amount); emit TRANSFER249(address(0), account, amount); } function _BURN126(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER183(account, address(0), amount); _balances[account] = _balances[account].SUB786(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB786(amount); emit TRANSFER249(account, address(0), amount); } function _APPROVE516(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL928(owner, spender, amount); } function _SETUPDECIMALS502(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER183(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // contract YieldDelegatingVaultEvent2 { event NEWTREASURY741(address oldTreasury, address newTreasury); //inject NONSTANDARD NAMING event NEWDELEGATEPERCENT315(uint256 oldDelegatePercent, uint256 newDelegatePercent); //inject NONSTANDARD NAMING event NEWREWARDPERTOKEN257(uint256 oldRewardPerToken, uint256 newRewardPerToken); //inject NONSTANDARD NAMING } // 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; } function _ADD330(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS441(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; } } function _REMOVE267(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS441(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH266(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT20(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD236(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD330(set._inner, bytes32(uint256(value))); } function REMOVE884(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE267(set._inner, bytes32(uint256(value))); } function CONTAINS556(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS441(set._inner, bytes32(uint256(value))); } function LENGTH118(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH266(set._inner); } function AT34(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT20(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD236(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD330(set._inner, bytes32(value)); } function REMOVE884(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE267(set._inner, bytes32(value)); } function CONTAINS556(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS441(set._inner, bytes32(value)); } function LENGTH118(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH266(set._inner); } function AT34(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT20(set._inner, index)); } } // abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant default_admin_role567 = 0x00; //inject NONSTANDARD NAMING event ROLEADMINCHANGED88(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING event ROLEGRANTED826(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING event ROLEREVOKED185(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING function HASROLE367(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING return _roles[role].members.CONTAINS556(account); } function GETROLEMEMBERCOUNT938(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING return _roles[role].members.LENGTH118(); } function GETROLEMEMBER19(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _roles[role].members.AT34(index); } function GETROLEADMIN235(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING return _roles[role].adminRole; } function GRANTROLE137(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to grant"); _GRANTROLE954(role, account); } function REVOKEROLE670(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to revoke"); _REVOKEROLE460(role, account); } function RENOUNCEROLE777(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(account == _MSGSENDER905(), "AccessControl: can only renounce roles for self"); _REVOKEROLE460(role, account); } function _SETUPROLE461(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING _GRANTROLE954(role, account); } function _SETROLEADMIN512(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING emit ROLEADMINCHANGED88(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _GRANTROLE954(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.ADD236(account)) { emit ROLEGRANTED826(role, account, _MSGSENDER905()); } } function _REVOKEROLE460(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.REMOVE884(account)) { emit ROLEREVOKED185(role, account, _MSGSENDER905()); } } } // contract YDVRewardsDistributor is AccessControl, Ownable { using SafeERC20 for IERC20; using Address for address; IERC20 public rewardToken; address[] public ydvs; bytes32 public constant ydv_rewards665 = keccak256("YDV_REWARDS"); //inject NONSTANDARD NAMING constructor(address _rally) public { rewardToken = IERC20(_rally); _SETUPROLE461(default_admin_role567, msg.sender); } function TRANSFERREWARD486(uint256 _amount) external { //inject NONSTANDARD NAMING require (HASROLE367(ydv_rewards665, msg.sender), "only ydv rewards"); rewardToken.SAFETRANSFER115(msg.sender, _amount); } function ADDYDV918(address _ydv) external ONLYOWNER378 { //inject NONSTANDARD NAMING GRANTROLE137(ydv_rewards665, _ydv); ydvs.push(_ydv); } function YDVSLENGTH403() external view returns (uint256) { //inject NONSTANDARD NAMING return ydvs.length; } } // interface Vault { function BALANCEOF1000(address) external view returns (uint256); //inject NONSTANDARD NAMING function TOKEN783() external view returns (address); //inject NONSTANDARD NAMING function CLAIMINSURANCE535() external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE194() external view returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT941(uint) external; //inject NONSTANDARD NAMING function WITHDRAW419(uint) external; //inject NONSTANDARD NAMING } // contract YDVErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, REJECTION } enum FailureInfo { SET_INDIVIDUAL_SOFT_CAP_CHECK, SET_GLOBAL_SOFT_CAP_CHECK } event FAILURE308(uint error, uint info, uint detail); //inject NONSTANDARD NAMING function FAIL273(Error err, FailureInfo info) internal returns (uint) { //inject NONSTANDARD NAMING emit FAILURE308(uint(err), uint(info), 0); return uint(err); } function FAILOPAQUE544(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { //inject NONSTANDARD NAMING emit FAILURE308(uint(err), uint(info), opaqueError); return uint(err); } } // contract RallyToken is ERC20 { //15 billion fixed token supply with default 18 decimals uint256 public constant token_supply159 = 15 * 10**9 * 10**18; //inject NONSTANDARD NAMING constructor ( address _escrow ) public ERC20( "Rally", "RLY" ) { _MINT985(_escrow, token_supply159); } } // contract NoMintLiquidityRewardPools is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of RLY // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRallyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRallyPerShare` (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 { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. RLYs to distribute per block. uint256 lastRewardBlock; // Last block number that RLYs distribution occurs. uint256 accRallyPerShare; // Accumulated RLYs per share, times 1e12. See below. } // The RALLY TOKEN! RallyToken public rally; // RLY tokens created per block. uint256 public rallyPerBlock; // 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 RLY mining starts. uint256 public startBlock; event DEPOSIT927(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW385(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW903(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING constructor( RallyToken _rally, uint256 _rallyPerBlock, uint256 _startBlock ) public { rally = _rally; rallyPerBlock = _rallyPerBlock; startBlock = _startBlock; } function POOLLENGTH610() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // 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 ADD236(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING if (_withUpdate) { MASSUPDATEPOOLS681(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.ADD236(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRallyPerShare: 0 })); } // Update the given pool's RLY allocation point. Can only be called by the owner. function SET138(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING if (_withUpdate) { MASSUPDATEPOOLS681(); } totalAllocPoint = totalAllocPoint.SUB786(poolInfo[_pid].allocPoint).ADD236(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // update the rate at which RLY is allocated to rewards, can only be called by the owner function SETRALLYPERBLOCK200(uint256 _rallyPerBlock) public ONLYOWNER378 { //inject NONSTANDARD NAMING MASSUPDATEPOOLS681(); rallyPerBlock = _rallyPerBlock; } // View function to see pending RLYs on frontend. function PENDINGRALLY232(uint256 _pid, address _user) external view returns (uint256) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRallyPerShare = pool.accRallyPerShare; uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = block.number.SUB786(pool.lastRewardBlock); uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint); accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply)); } return user.amount.MUL747(accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS681() public { //inject NONSTANDARD NAMING uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { UPDATEPOOL112(pid); } } // Update reward variables of the given pool to be up-to-date. // No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract function UPDATEPOOL112(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = block.number.SUB786(pool.lastRewardBlock); uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint); pool.accRallyPerShare = pool.accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to pool for RLY allocation. function DEPOSIT941(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; UPDATEPOOL112(_pid); if (user.amount > 0) { uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt); if(pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.SAFETRANSFERFROM287(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD236(_amount); } user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12); emit DEPOSIT927(msg.sender, _pid, _amount); } // Withdraw LP tokens from pool. function WITHDRAW419(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); UPDATEPOOL112(_pid); uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt); if(pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.SUB786(_amount); pool.lpToken.SAFETRANSFER115(address(msg.sender), _amount); } user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12); emit WITHDRAW385(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function EMERGENCYWITHDRAW757(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.SAFETRANSFER115(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW903(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe RLY transfer function, just in case pool does not have enough RLY; either rounding error or we're not supplying more rewards function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING uint256 rallyBal = rally.BALANCEOF1000(address(this)); if (_amount > rallyBal) { rally.TRANSFER912(_to, rallyBal); } else { rally.TRANSFER912(_to, _amount); } } } // contract YieldDelegatingVaultStorage2 { address public vault; YDVRewardsDistributor rewards; IERC20 public rally; address public treasury; IERC20 public token; uint256 public delegatePercent; mapping(address => uint256) public rewardDebt; uint256 public totalDeposits; uint256 public rewardPerToken; uint256 public accRallyPerShare; bool public lrEnabled; uint256 public pid; NoMintLiquidityRewardPools lrPools; } // contract YieldDelegatingVault2 is ERC20, YieldDelegatingVaultStorage2, YieldDelegatingVaultEvent2, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; constructor ( address _vault, address _rewards, address _treasury, uint256 _delegatePercent, uint256 _rewardPerToken ) public ERC20( string(abi.encodePacked("rally delegating ", ERC20(Vault(_vault).TOKEN783()).NAME654())), string(abi.encodePacked("rd", ERC20(Vault(_vault).TOKEN783()).SYMBOL381())) ) { _SETUPDECIMALS502(ERC20(Vault(_vault).TOKEN783()).DECIMALS442()); token = IERC20(Vault(_vault).TOKEN783()); //token being deposited in the referenced vault vault = _vault; //address of the vault we're proxying rewards = YDVRewardsDistributor(_rewards); rally = rewards.rewardToken(); treasury = _treasury; delegatePercent = _delegatePercent; rewardPerToken = _rewardPerToken; totalDeposits = 0; accRallyPerShare = 0; lrEnabled = false; } function SETTREASURY672(address newTreasury) public ONLYOWNER378 { //inject NONSTANDARD NAMING require(newTreasury != address(0), "treasure should be valid address"); address oldTreasury = treasury; treasury = newTreasury; emit NEWTREASURY741(oldTreasury, newTreasury); } function SETNEWREWARDPERTOKEN724(uint256 newRewardPerToken) public ONLYOWNER378 { //inject NONSTANDARD NAMING uint256 oldRewardPerToken = rewardPerToken; rewardPerToken = newRewardPerToken; emit NEWREWARDPERTOKEN257(oldRewardPerToken, newRewardPerToken); } function EARNED974(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEFORREWARDSCALC156(account).MUL747(accRallyPerShare).DIV140(1e12).SUB786(rewardDebt[account]); } function BALANCE265() public view returns (uint256) { //inject NONSTANDARD NAMING return (IERC20(vault)).BALANCEOF1000(address(this)); //how many shares do we have in the vault we are delegating to } //for the purpose of rewards calculations, a user's balance is the total of what's in their wallet //and what they have deposited in the rewards pool (if it's active). //transfer restriction ensures accuracy of this sum function BALANCEFORREWARDSCALC156(address account) internal view returns (uint256) { //inject NONSTANDARD NAMING if (lrEnabled) { (uint256 amount, ) = lrPools.userInfo(pid, account); return BALANCEOF1000(account).ADD236(amount); } return BALANCEOF1000(account); } function DEPOSITALL490() external { //inject NONSTANDARD NAMING DEPOSIT941(token.BALANCEOF1000(msg.sender)); } function DEPOSIT941(uint256 _amount) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 _pool = BALANCE265(); uint256 _before = token.BALANCEOF1000(address(this)); token.SAFETRANSFERFROM287(msg.sender, address(this), _amount); uint256 _after = token.BALANCEOF1000(address(this)); _amount = _after.SUB786(_before); totalDeposits = totalDeposits.ADD236(_amount); token.APPROVE378(vault, _amount); Vault(vault).DEPOSIT941(_amount); uint256 _after_pool = BALANCE265(); uint256 _new_shares = _after_pool.SUB786(_pool); //new vault tokens representing my added vault shares //translate vault shares into delegating vault shares uint256 shares = 0; if (TOTALSUPPLY709() == 0) { shares = _new_shares; } else { shares = (_new_shares.MUL747(TOTALSUPPLY709())).DIV140(_pool); } _MINT985(msg.sender, shares); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); } function DEPOSITYTOKEN556(uint256 _yamount) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 _before = IERC20(vault).BALANCEOF1000(address(this)); IERC20(vault).SAFETRANSFERFROM287(msg.sender, address(this), _yamount); uint256 _after = IERC20(vault).BALANCEOF1000(address(this)); _yamount = _after.SUB786(_before); uint _underlyingAmount = _yamount.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); totalDeposits = totalDeposits.ADD236(_underlyingAmount); //translate vault shares into delegating vault shares uint256 shares = 0; if (TOTALSUPPLY709() == 0) { shares = _yamount; } else { shares = (_yamount.MUL747(TOTALSUPPLY709())).DIV140(_before); } _MINT985(msg.sender, shares); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); } function WITHDRAWALL908() external { //inject NONSTANDARD NAMING WITHDRAW419(BALANCEOF1000(msg.sender)); } function WITHDRAW419(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709()); _BURN126(msg.sender, _shares); SAFEREDUCETOTALDEPOSITS144(r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18)); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); uint256 _before = token.BALANCEOF1000(address(this)); Vault(vault).WITHDRAW419(r); uint256 _after = token.BALANCEOF1000(address(this)); uint256 toTransfer = _after.SUB786(_before); token.SAFETRANSFER115(msg.sender, toTransfer); } //in case of rounding errors converting between vault tokens and underlying value function SAFEREDUCETOTALDEPOSITS144(uint256 _amount) internal { //inject NONSTANDARD NAMING if (_amount > totalDeposits) { totalDeposits = 0; } else { totalDeposits = totalDeposits.SUB786(_amount); } } function WITHDRAWYTOKEN466(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709()); _BURN126(msg.sender, _shares); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); uint256 _amount = r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); SAFEREDUCETOTALDEPOSITS144(_amount); IERC20(vault).SAFETRANSFER115(msg.sender, r); } // Safe RLY transfer function, just in case pool does not have enough RLY due to rounding error function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING uint256 rallyBal = rally.BALANCEOF1000(address(this)); if (_amount > rallyBal) { rally.TRANSFER912(_to, rallyBal); } else { rally.TRANSFER912(_to, _amount); } } //how much are our shares of the underlying vault worth relative to the deposit value? returns value denominated in vault tokens function AVAILABLEYIELD882() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 totalValue = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); if (totalValue > totalDeposits) { uint256 earnings = totalValue.SUB786(totalDeposits); return earnings.MUL747(1e18).DIV140(Vault(vault).GETPRICEPERFULLSHARE194()); } return 0; } //transfer accumulated yield to treasury, update totalDeposits to ensure availableYield following //harvest is 0, and increase accumulated rally rewards //harvest fails if we're unable to fund rewards function HARVEST82() public ONLYOWNER378 { //inject NONSTANDARD NAMING uint256 _availableYield = AVAILABLEYIELD882(); if (_availableYield > 0) { uint256 rallyReward = _availableYield.MUL747(delegatePercent).DIV140(10000).MUL747(rewardPerToken).DIV140(1e18); rewards.TRANSFERREWARD486(rallyReward); IERC20(vault).SAFETRANSFER115(treasury, _availableYield.MUL747(delegatePercent).DIV140(10000)); accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(TOTALSUPPLY709())); totalDeposits = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); } } //one way ticket and only callable once function ENABLELIQUIDITYREWARDS505(address _lrPools, uint256 _pid) public ONLYOWNER378 { //inject NONSTANDARD NAMING (IERC20 lpToken,,,) = NoMintLiquidityRewardPools(_lrPools).poolInfo(_pid); require(address(lpToken) == address(this), "invalid liquidity rewards setup"); require(lrEnabled == false, "liquidity rewards already enabled"); lrEnabled = true; lrPools = NoMintLiquidityRewardPools(_lrPools); pid = _pid; } //override underlying _transfer implementation; YDV shares can only be transferred to/from the liquidity rewards pool function _TRANSFER205(address sender, address recipient, uint256 amount) internal override { //inject NONSTANDARD NAMING require(lrEnabled, "transfer rejected"); require(sender == address(lrPools) || recipient == address(lrPools), "transfer rejected"); super._TRANSFER205(sender, recipient, amount); } }
inject NONSTANDARD NAMING
function DEPOSIT941(uint256 _pid, uint256 _amount) public {
12,852,220
/* eToro Educational Crypto Based Arbitrage Signals - Learn how to leverage fractional shares of highly valuable assets to earn passive income. - Get automated arbitrage indicators to take advantage of cross-chain opportunities - 0% Risk Sessions - Minimum equity of $200 in crypto currency required - Daily Live Trading - Private Q&A Groups Join over 25M people on the world's largest social investing platform. https://t.me/eToroPortal Crypto Trading is offered via eToro LLC USA. Securities trading is offered via eToro USA Securities, Inc.("The BD"), a broker dealer registered with the Securities and Exchange Commission (SEC). The BD is a member of the Financial Industry Regulatory Authority (FINRA) and Securities Investor Protection Corporation (SIPC). eToro USA LLC (NMLS ID: 1769299 ) is not a registered broker-dealer or FINRA member and your cryptocurrency holdings are not FDIC or SIPC insured. eToro. © 2022 */ // SPDX-License-Identifier: MIT pragma solidity =0.8.10 >=0.8.0 <0.9.0; pragma experimental ABIEncoderV2; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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() { _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); } } 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); 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); /** * @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); } 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; 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; } 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; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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); } 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); } 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 _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } 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); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (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); } } } } 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); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } ////// src/IUniswapV2Factory.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } ////// src/IUniswapV2Pair.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } ////// src/IUniswapV2Router02.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function 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; } contract etoroarbi is Ownable, IERC20 { address UNISWAPROUTER = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address DEAD = 0x000000000000000000000000000000000000dEaD; address ZERO = 0x0000000000000000000000000000000000000000; string private _name = "eToro"; string private _symbol = "ETORO"; uint256 public treasuryFeeBPS = 100; uint256 public liquidityFeeBPS = 50; uint256 public dividendFeeBPS = 1450; uint256 public totalFeeBPS = 1600; uint256 public swapTokensAtAmount = 100000 * (10**18); uint256 public lastSwapTime; bool swapAllToken = true; bool public swapEnabled = true; bool public taxEnabled = true; bool public compoundingEnabled = true; bool public arbitrageEnabled = true; uint256 private _totalSupply; bool private swapping; address marketingWallet; address liquidityWallet; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public automatedMarketMakerPairs; mapping(address => bool) private _whiteList; mapping(address => bool) isBlacklisted; event SwapAndAddLiquidity( uint256 tokensSwapped, uint256 nativeReceived, uint256 tokensIntoLiquidity ); event SendDividends(uint256 tokensSwapped, uint256 amount); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event SwapEnabled(bool enabled); event TaxEnabled(bool enabled); event CompoundingEnabled(bool enabled); event BlacklistEnabled(bool enabled); DividendTracker public dividendTracker; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; uint256 public maxTxBPS = 75; uint256 public maxWalletBPS = 300; bool isOpen = false; mapping(address => bool) private _isExcludedFromMaxTx; mapping(address => bool) private _isExcludedFromMaxWallet; constructor( address _marketingWallet, address _liquidityWallet, address[] memory whitelistAddress ) { marketingWallet = _marketingWallet; liquidityWallet = _liquidityWallet; includeToWhiteList(whitelistAddress); dividendTracker = new DividendTracker(address(this), UNISWAPROUTER); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(UNISWAPROUTER); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker), true); dividendTracker.excludeFromDividends(address(this), true); dividendTracker.excludeFromDividends(owner(), true); dividendTracker.excludeFromDividends(address(_uniswapV2Router), true); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(dividendTracker), true); excludeFromMaxTx(owner(), true); excludeFromMaxTx(address(this), true); excludeFromMaxTx(address(dividendTracker), true); excludeFromMaxWallet(owner(), true); excludeFromMaxWallet(address(this), true); excludeFromMaxWallet(address(dividendTracker), true); _mint(owner(), 1000000000 * (10**18)); } receive() external payable {} function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERROR: decreased allowance below zero" ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } 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, "ERROR: transfer amount exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function openTrading() external onlyOwner { isOpen = true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require( isOpen || sender == owner() || recipient == owner() || _whiteList[sender] || _whiteList[recipient], "Not Open" ); require(!isBlacklisted[sender], "ERROR: Sender is blacklisted"); require(!isBlacklisted[recipient], "ERROR: Recipient is blacklisted"); require(sender != address(0), "ERROR: transfer from the zero address"); require(recipient != address(0), "ERROR: transfer to the zero address"); uint256 _maxTxAmount = (totalSupply() * maxTxBPS) / 10000; uint256 _maxWallet = (totalSupply() * maxWalletBPS) / 10000; require( amount <= _maxTxAmount || _isExcludedFromMaxTx[sender], "TX Limit Exceeded" ); if ( sender != owner() && recipient != address(this) && recipient != address(DEAD) && recipient != uniswapV2Pair ) { uint256 currentBalance = balanceOf(recipient); require( _isExcludedFromMaxWallet[recipient] || (currentBalance + amount <= _maxWallet) ); } uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERROR: transfer amount exceeds balance" ); uint256 contractTokenBalance = balanceOf(address(this)); uint256 contractNativeBalance = address(this).balance; bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( swapEnabled && // True canSwap && // true !swapping && // swapping=false !false true !automatedMarketMakerPairs[sender] && // no swap on remove liquidity step 1 or DEX buy sender != address(uniswapV2Router) && // no swap on remove liquidity step 2 sender != owner() && recipient != owner() ) { swapping = true; if (!swapAllToken) { contractTokenBalance = swapTokensAtAmount; } _executeSwap(contractTokenBalance, contractNativeBalance); lastSwapTime = block.timestamp; swapping = false; } bool takeFee; if ( sender == address(uniswapV2Pair) || recipient == address(uniswapV2Pair) ) { takeFee = true; } if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (swapping || !taxEnabled) { takeFee = false; } if (takeFee) { uint256 fees = (amount * totalFeeBPS) / 10000; amount -= fees; _executeTransfer(sender, address(this), fees); } _executeTransfer(sender, recipient, amount); dividendTracker.setBalance(payable(sender), balanceOf(sender)); dividendTracker.setBalance(payable(recipient), balanceOf(recipient)); } function _executeTransfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERROR: transfer from the zero address"); require(recipient != address(0), "ERROR: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERROR: transfer amount exceeds balance" ); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERROR: approve from the zero address"); require(spender != address(0), "ERROR: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _mint(address account, uint256 amount) private { require(account != address(0), "ERROR: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) private { require(account != address(0), "ERROR: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERROR: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function swapTokensForNative(uint256 tokens) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokens); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokens, 0, // accept any amount of native path, address(this), block.timestamp ); } function addLiquidity(uint256 tokens, uint256 native) private { _approve(address(this), address(uniswapV2Router), tokens); uniswapV2Router.addLiquidityETH{value: native}( address(this), tokens, 0, // slippage unavoidable 0, // slippage unavoidable liquidityWallet, block.timestamp ); } function includeToWhiteList(address[] memory _users) private { for (uint8 i = 0; i < _users.length; i++) { _whiteList[_users[i]] = true; } } function _executeSwap(uint256 tokens, uint256 native) private { if (tokens <= 0) { return; } uint256 swapTokensMarketing; if (address(marketingWallet) != address(0)) { swapTokensMarketing = (tokens * treasuryFeeBPS) / totalFeeBPS; } uint256 swapTokensDividends; if (dividendTracker.totalSupply() > 0) { swapTokensDividends = (tokens * dividendFeeBPS) / totalFeeBPS; } uint256 tokensForLiquidity = tokens - swapTokensMarketing - swapTokensDividends; uint256 swapTokensLiquidity = tokensForLiquidity / 2; uint256 addTokensLiquidity = tokensForLiquidity - swapTokensLiquidity; uint256 swapTokensTotal = swapTokensMarketing + swapTokensDividends + swapTokensLiquidity; uint256 initNativeBal = address(this).balance; swapTokensForNative(swapTokensTotal); uint256 nativeSwapped = (address(this).balance - initNativeBal) + native; uint256 nativeMarketing = (nativeSwapped * swapTokensMarketing) / swapTokensTotal; uint256 nativeDividends = (nativeSwapped * swapTokensDividends) / swapTokensTotal; uint256 nativeLiquidity = nativeSwapped - nativeMarketing - nativeDividends; if (nativeMarketing > 0) { payable(marketingWallet).transfer(nativeMarketing); } addLiquidity(addTokensLiquidity, nativeLiquidity); emit SwapAndAddLiquidity( swapTokensLiquidity, nativeLiquidity, addTokensLiquidity ); if (nativeDividends > 0) { (bool success, ) = address(dividendTracker).call{ value: nativeDividends }(""); if (success) { emit SendDividends(swapTokensDividends, nativeDividends); } } } function excludeFromFees(address account, bool excluded) public onlyOwner { require( _isExcludedFromFees[account] != excluded, "ERROR: account is already set to requested state" ); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function manualSendDividend(uint256 amount, address holder) external onlyOwner { dividendTracker.manualSendDividend(amount, holder); } function excludeFromDividends(address account, bool excluded) public onlyOwner { dividendTracker.excludeFromDividends(account, excluded); } function isExcludedFromDividends(address account) public view returns (bool) { return dividendTracker.isExcludedFromDividends(account); } function setWallet( address payable _marketingWallet, address payable _arbitrageWallet ) external onlyOwner { marketingWallet = _marketingWallet; liquidityWallet = _arbitrageWallet; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "ERROR: DEX pair can not be removed"); _setAutomatedMarketMakerPair(pair, value); } function setFee( uint256 _treasuryFee, uint256 _liquidityFee, uint256 _dividendFee ) external onlyOwner { treasuryFeeBPS = _treasuryFee; liquidityFeeBPS = _liquidityFee; dividendFeeBPS = _dividendFee; totalFeeBPS = _treasuryFee + _liquidityFee + _dividendFee; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require( automatedMarketMakerPairs[pair] != value, "ERROR: automated market maker pair is already set to that value" ); automatedMarketMakerPairs[pair] = value; if (value) { dividendTracker.excludeFromDividends(pair, true); } emit SetAutomatedMarketMakerPair(pair, value); } function updateUniswapV2Router(address newAddress) public onlyOwner { require( newAddress != address(uniswapV2Router), "ERROR: the router is already set to the new address" ); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); uniswapV2Pair = _uniswapV2Pair; } function claim() public { dividendTracker.processAccount(payable(_msgSender())); } function arbitrage() public { require(compoundingEnabled, "ERROR: compounding is not enabled"); dividendTracker.compoundAccount(payable(_msgSender())); } function withdrawableDividendOf(address account) public view returns (uint256) { return dividendTracker.withdrawableDividendOf(account); } function withdrawnDividendOf(address account) public view returns (uint256) { return dividendTracker.withdrawnDividendOf(account); } function accumulativeDividendOf(address account) public view returns (uint256) { return dividendTracker.accumulativeDividendOf(account); } function getAccountInfo(address account) public view returns ( address, uint256, uint256, uint256, uint256 ) { return dividendTracker.getAccountInfo(account); } function getLastClaimTime(address account) public view returns (uint256) { return dividendTracker.getLastClaimTime(account); } function setSwapEnabled(bool _enabled) external onlyOwner { swapEnabled = _enabled; emit SwapEnabled(_enabled); } function setTaxEnabled(bool _enabled) external onlyOwner { taxEnabled = _enabled; emit TaxEnabled(_enabled); } function setCompoundingEnabled(bool _enabled) external onlyOwner { compoundingEnabled = _enabled; emit CompoundingEnabled(_enabled); } function setArbitrageEnabled(bool _enabled) external onlyOwner { arbitrageEnabled = _enabled; } function updateDividendSettings( bool _swapEnabled, uint256 _swapTokensAtAmount, bool _swapAllToken ) external onlyOwner { swapEnabled = _swapEnabled; swapTokensAtAmount = _swapTokensAtAmount; swapAllToken = _swapAllToken; } function setMaxTxLimit(uint256 limit) external onlyOwner { require(limit >= 75 && limit <= 10000, "LIMIT must be between 75 and 10000"); maxTxBPS = limit; } function excludeFromMaxTx(address account, bool excluded) public onlyOwner { _isExcludedFromMaxTx[account] = excluded; } function isExcludedFromMaxTx(address account) public view returns (bool) { return _isExcludedFromMaxTx[account]; } function setMaxWallet(uint256 limit) external onlyOwner { require( limit >= 175 && limit <= 10000, "LIMIT must be between 175 and 10000" ); maxWalletBPS = limit; } function excludeFromMaxWallet(address account, bool excluded) public onlyOwner { _isExcludedFromMaxWallet[account] = excluded; } function isExcludedFromMaxWallet(address account) public view returns (bool) { return _isExcludedFromMaxWallet[account]; } function rescueToken(address _token, uint256 _amount) external onlyOwner { IERC20(_token).transfer(msg.sender, _amount); } function rescueETH(uint256 _amount) external onlyOwner { payable(msg.sender).transfer(_amount); } function blackList(address _user) public onlyOwner { require(!isBlacklisted[_user], "user already blacklisted"); isBlacklisted[_user] = true; // events? } function removeFromBlacklist(address _user) public onlyOwner { require(isBlacklisted[_user], "user already whitelisted"); isBlacklisted[_user] = false; //events? } function blackListMany(address[] memory _users) public onlyOwner { for (uint8 i = 0; i < _users.length; i++) { isBlacklisted[_users[i]] = true; } } function unBlackListMany(address[] memory _users) public onlyOwner { for (uint8 i = 0; i < _users.length; i++) { isBlacklisted[_users[i]] = false; } } } contract DividendTracker is Ownable, IERC20 { address UNISWAPROUTER; string private _name = "Investor_DividendTracker"; string private _symbol = "Investor_DividendTracker"; uint256 public lastProcessedIndex; uint256 private _totalSupply; mapping(address => uint256) private _balances; uint256 private constant magnitude = 2**128; uint256 public immutable minTokenBalanceForDividends; uint256 private magnifiedDividendPerShare; uint256 public totalDividendsDistributed; uint256 public totalDividendsWithdrawn; address public tokenAddress; mapping(address => bool) public excludedFromDividends; mapping(address => int256) private magnifiedDividendCorrections; mapping(address => uint256) private withdrawnDividends; mapping(address => uint256) private lastClaimTimes; event DividendsDistributed(address indexed from, uint256 weiAmount); event DividendWithdrawn(address indexed to, uint256 weiAmount); event ExcludeFromDividends(address indexed account, bool excluded); event Claim(address indexed account, uint256 amount); event Compound(address indexed account, uint256 amount, uint256 tokens); struct AccountInfo { address account; uint256 withdrawableDividends; uint256 totalDividends; uint256 lastClaimTime; } constructor(address _tokenAddress, address _uniswapRouter) { minTokenBalanceForDividends = 10000 * (10**18); tokenAddress = _tokenAddress; UNISWAPROUTER = _uniswapRouter; } receive() external payable { distributeDividends(); } function distributeDividends() public payable { require(_totalSupply > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare + ((msg.value * magnitude) / _totalSupply); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed += msg.value; } } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if (excludedFromDividends[account]) { return; } if (newBalance >= minTokenBalanceForDividends) { _setBalance(account, newBalance); } else { _setBalance(account, 0); } } function excludeFromDividends(address account, bool excluded) external onlyOwner { require( excludedFromDividends[account] != excluded, "Investor_DividendTracker: account already set to requested state" ); excludedFromDividends[account] = excluded; if (excluded) { _setBalance(account, 0); } else { uint256 newBalance = IERC20(tokenAddress).balanceOf(account); if (newBalance >= minTokenBalanceForDividends) { _setBalance(account, newBalance); } else { _setBalance(account, 0); } } emit ExcludeFromDividends(account, excluded); } function isExcludedFromDividends(address account) public view returns (bool) { return excludedFromDividends[account]; } function manualSendDividend(uint256 amount, address holder) external onlyOwner { uint256 contractETHBalance = address(this).balance; payable(holder).transfer(amount > 0 ? amount : contractETHBalance); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = _balances[account]; if (newBalance > currentBalance) { uint256 addAmount = newBalance - currentBalance; _mint(account, addAmount); } else if (newBalance < currentBalance) { uint256 subAmount = currentBalance - newBalance; _burn(account, subAmount); } } function _mint(address account, uint256 amount) private { require( account != address(0), "Investor_DividendTracker: mint to the zero address" ); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] - int256(magnifiedDividendPerShare * amount); } function _burn(address account, uint256 amount) private { require( account != address(0), "Investor_DividendTracker: burn from the zero address" ); uint256 accountBalance = _balances[account]; require( accountBalance >= amount, "Investor_DividendTracker: burn amount exceeds balance" ); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] + int256(magnifiedDividendPerShare * amount); } function processAccount(address payable account) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount); return true; } return false; } function _withdrawDividendOfUser(address payable account) private returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(account); if (_withdrawableDividend > 0) { withdrawnDividends[account] += _withdrawableDividend; totalDividendsWithdrawn += _withdrawableDividend; emit DividendWithdrawn(account, _withdrawableDividend); (bool success, ) = account.call{ value: _withdrawableDividend, gas: 3000 }(""); if (!success) { withdrawnDividends[account] -= _withdrawableDividend; totalDividendsWithdrawn -= _withdrawableDividend; return 0; } return _withdrawableDividend; } return 0; } function compoundAccount(address payable account) public onlyOwner returns (bool) { (uint256 amount, uint256 tokens) = _compoundDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Compound(account, amount, tokens); return true; } return false; } function _compoundDividendOfUser(address payable account) private returns (uint256, uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(account); if (_withdrawableDividend > 0) { withdrawnDividends[account] += _withdrawableDividend; totalDividendsWithdrawn += _withdrawableDividend; emit DividendWithdrawn(account, _withdrawableDividend); IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02( UNISWAPROUTER ); address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(tokenAddress); bool success; uint256 tokens; uint256 initTokenBal = IERC20(tokenAddress).balanceOf(account); try uniswapV2Router .swapExactETHForTokensSupportingFeeOnTransferTokens{ value: _withdrawableDividend }(0, path, address(account), block.timestamp) { success = true; tokens = IERC20(tokenAddress).balanceOf(account) - initTokenBal; } catch Error( string memory /*err*/ ) { success = false; } if (!success) { withdrawnDividends[account] -= _withdrawableDividend; totalDividendsWithdrawn -= _withdrawableDividend; return (0, 0); } return (_withdrawableDividend, tokens); } return (0, 0); } function withdrawableDividendOf(address account) public view returns (uint256) { return accumulativeDividendOf(account) - withdrawnDividends[account]; } function withdrawnDividendOf(address account) public view returns (uint256) { return withdrawnDividends[account]; } function accumulativeDividendOf(address account) public view returns (uint256) { int256 a = int256(magnifiedDividendPerShare * balanceOf(account)); int256 b = magnifiedDividendCorrections[account]; // this is an explicit int256 (signed) return uint256(a + b) / magnitude; } function getAccountInfo(address account) public view returns ( address, uint256, uint256, uint256, uint256 ) { AccountInfo memory info; info.account = account; info.withdrawableDividends = withdrawableDividendOf(account); info.totalDividends = accumulativeDividendOf(account); info.lastClaimTime = lastClaimTimes[account]; return ( info.account, info.withdrawableDividends, info.totalDividends, info.lastClaimTime, totalDividendsWithdrawn ); } function getLastClaimTime(address account) public view returns (uint256) { return lastClaimTimes[account]; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return 18; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address, uint256) public pure override returns (bool) { revert("Investor_DividendTracker: method not implemented"); } function allowance(address, address) public pure override returns (uint256) { revert("Investor_DividendTracker: method not implemented"); } function approve(address, uint256) public pure override returns (bool) { revert("Investor_DividendTracker: method not implemented"); } function transferFrom( address, address, uint256 ) public pure override returns (bool) { revert("Investor_DividendTracker: method not implemented"); } }
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); } }
6,315,417
./full_match/80001/0xDDD767bAA4Ac0cCF04bf752f8669D2A08888A47e/sources/safeL2.sol
Allows to create new proxy contact using CREATE2 but it doesn't run the initializer. This method is only meant as an utility to be called from other methods _singleton Address of singleton contract. initializer Payload for message call sent to new proxy contract. saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it solhint-disable-next-line no-inline-assembly
function deployProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) internal returns (GnosisSafeProxy proxy) { bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce)); bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton))); assembly { proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt) } require(address(proxy) != address(0), "Create2 call failed"); }
850,188
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @notice Interface for Curve.fi's pool. */ interface ICurveFi { function get_virtual_price() external view returns (uint256); function remove_liquidity_one_coin(uint256 token_amount, int128 iint128, uint256 min_amount) external; // ren pool/hbtc pool function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; // sbtc pool function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; // obtc pool function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; }
Interface for Curve.fi's pool./ ren pool/hbtc pool sbtc pool obtc pool
interface ICurveFi { function get_virtual_price() external view returns (uint256); function remove_liquidity_one_coin(uint256 token_amount, int128 iint128, uint256 min_amount) external; function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; pragma solidity 0.8.0; }
2,557,059
// SPDX-License-Identifier: TERA pragma solidity ^0.7.3; import "./DataLib.sol"; contract ConvertLib is DataLib { //------------------------------------------------------------------------ //------------------------------------------------------------------------ function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function RevertBytes(uint Data) internal pure returns (uint Ret) { assembly { for { let i := 0 } lt(i, 32) { i := add(i, 1) } { Ret := mul(Ret,0x100) Ret := or(Ret,and(Data,0xFF)) Data := div(Data,0x100) } } } function GetAddrFromBytes(bytes memory Addr) internal pure returns (address) { require(Addr.length >= 20, "GetAddrFromBytes_outOfBounds"); uint160 addr=0; assembly { addr := div(mload(add(Addr,32)), 0x1000000000000000000000000) } return address(addr); } function GetAddrFromBytes20(bytes20 Addr) internal pure returns (address) { uint160 addr; assembly { addr := div(Addr, 0x1000000000000000000000000) } return address(addr); } //------------------------------------------------------------------------ function MemCpy(uint dest,uint src, uint16 size) internal pure { // Copy word-length chunks while possible for(; size >= 32; size -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - size) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } //------------------------------------------------------------------------ //-------------------------------- TERA decode library for Solidity //------------------------------------------------------------------------ function GetBufPos(bytes memory Buf) pure internal returns (uint Ret) { assembly { Ret := add(Buf,32) } } //------------------------------------------------------------------------ function GetBytes32(uint Data) internal pure returns (bytes32 RetArr) { assembly { RetArr := mload(Data) } } function GetBytes20(uint Data) internal pure returns (bytes20 RetArr) { assembly { RetArr := mload(Data) RetArr := and(RetArr, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } function GetBytes10(uint Data) internal pure returns (bytes10 RetArr) { assembly { RetArr := mload(Data) RetArr := and(RetArr, 0xFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000) } } function GetBytes(uint Data, uint16 size) internal pure returns (bytes memory RetArr) { RetArr=new bytes(size); uint dest; assembly { dest := add(RetArr, 0x20) } MemCpy(dest,Data,size); } function Bytes32FromBytes(bytes memory Data) internal pure returns (bytes32 RetArr) { uint ShrCount; if(Data.length<32) ShrCount=8*(32-Data.length); assembly { RetArr := mload(add(Data, 0x20)) RetArr := shr(ShrCount,RetArr) } } function UintFromBytes(bytes memory Data) internal pure returns (uint RetArr) { uint ShrCount; if(Data.length==0) return 0; if(Data.length<32) ShrCount=8*(32-Data.length); assembly { RetArr := mload(add(Data, 0x20)) RetArr := shr(ShrCount,RetArr) } } function UintFromBytes10(bytes memory Data) internal pure returns (uint Ret) { uint256 value = UintFromBytes(Data); uint256 Mult=1; while (value != 0) { uint256 B=value%16; require(B<10, "UintFromBytes10: Received a character in the range A-F"); Ret = Ret + B*Mult; Mult = Mult*10; value = value >> 4; } } function GetUint1(uint Data) internal pure returns (uint8 Num) { assembly { Num := shr(248,mload(Data)) } } function GetUint2(uint Data) internal pure returns (uint16 Num) { assembly { Num := shr(240,mload(Data)) } } function GetUint3(uint Data) internal pure returns (uint24 Num) { assembly { Num := shr(232,mload(Data)) } } function GetUint4(uint Data) internal pure returns (uint32 Num) { assembly { Num := shr(224,mload(Data)) } } function GetUint5(uint Data) internal pure returns (uint40 Num) { assembly { Num := shr(216,mload(Data)) } } function GetUint6(uint Data) internal pure returns (uint48 Num) { assembly { Num := shr(208,mload(Data)) } } function GetUint8(uint Data) internal pure returns (uint64 Num) { assembly { Num := shr(192,mload(Data)) } } //------------------------------------------------------------------------ //-------------------------------- TERA encode library for Solidity //------------------------------------------------------------------------ function EncodeUint(uint Buf,uint256 Value,uint16 size) pure internal { uint16 rotate=256-size*8; assembly { mstore(Buf, shl(rotate,Value)) } } function EncodeArrConst(uint Buf,bytes32 Value) pure internal { assembly { mstore(Buf, Value) } } function EncodeBytes(uint Buf,bytes memory Value) pure internal { uint16 size=uint16(Value.length); uint src; assembly { src := add(Value, 0x20) } MemCpy(Buf,src,size); } //------------------------------------------------------------------------ //Order lib //------------------------------------------------------------------------ function CheckBufPos(bytes memory Buf,uint BufPos) pure internal { uint StartPos; assembly { StartPos := add(Buf,32) } StartPos+=Buf.length; require(StartPos>=BufPos,"Error BufPos"); } //SizeMode: 2-from store,3-from extern tx function FillOrderBody(TypeOrder memory Order, bytes memory Buf, uint SizeMode) internal pure { /* TERA: Order.Gate=DecodeUint(Buf,4); Order.ID=DecodeUint(Buf,6); Order.AddrTera=DecodeUint(Buf,4); Order.AddrEth=GetHexFromArr(DecodeArrConst(Buf,20)); Order.TokenID=GetHexFromArr(DecodeArr(Buf)); Order.Amount=DecodeUint(Buf,8)/1e9; Order.TransferFee=DecodeUint(Buf,8)/1e9; Order.Description=DecodeStr(Buf); */ require(SizeMode>=BUF_STORE,"FillOrderBody:SizeMode error"); uint MustMinLength=4+6+4+20 +2 +8+8+2; if(SizeMode==BUF_EXTERN_FULL) MustMinLength+= 1+66; if(SizeMode==BUF_STORE) MustMinLength+= 1+66 + 8; //BUF_EXTERN_HEADER - not add require(Buf.length>=MustMinLength,"Error FillOrderBody Data length"); uint16 size; uint BufPos=GetBufPos(Buf); Order.Gate=GetUint4(BufPos); BufPos+=4; Order.ID=GetUint6(BufPos); BufPos+=6; Order.AddrTera=GetUint4(BufPos); BufPos+=4; Order.AddrEth=GetBytes20(BufPos);BufPos+=20; size=GetUint2(BufPos);BufPos+=2; Order.TokenID=GetBytes(BufPos,size);BufPos+=size; Order.Amount=GetUint8(BufPos); BufPos+=8; Order.TransferFee=GetUint8(BufPos); BufPos+=8; size=GetUint2(BufPos);BufPos+=2; Order.Description=GetBytes(BufPos,size);BufPos+=size; if(SizeMode==BUF_EXTERN_HEADER)//data from tx AddOrder { CheckBufPos(Buf,BufPos); return; } size=GetUint1(BufPos); BufPos++; if(size>0) { Order.SignArr=new TypeSigner[](size); for(uint8 i=0;i<size;i++) { TypeSigner memory Item=Order.SignArr[i]; Item.Notary=GetUint1(BufPos); BufPos++; Item.SignR=GetBytes32(BufPos);BufPos+=32; Item.SignS=GetBytes32(BufPos);BufPos+=32; Item.SignV=GetUint1(BufPos);BufPos++; } } if(SizeMode==BUF_EXTERN_FULL)//data from tx ExecOrder { CheckBufPos(Buf,BufPos); return; } //data from state Order.NotaryFee=GetUint8(BufPos); BufPos+=8; CheckBufPos(Buf,BufPos); } //SizeMode: 1-for sign, 2-for save to store,3-for extern use (get full info) function GetBufFromOrder(TypeOrder memory Order,uint SizeMode) pure internal returns (bytes memory) { /* TERA: EncodeUint(Buf,Order.Gate,4); EncodeUint(Buf,Order.ID,6); EncodeUint(Buf,Order.AddrTera,4); EncodeArrConst(Buf,Order.AddrEth,20); EncodeArr(Buf,Order.TokenID); EncodeUint(Buf,FromFloat(Order.Amount),8); EncodeUint(Buf,FromFloat(Order.TransferFee),8); EncodeStr(Buf,Order.Description); */ require(SizeMode>0,"GetBufFromOrder:SizeMode error"); uint32 size1=uint32(Order.TokenID.length); uint32 size2=uint32(Order.Description.length); uint32 size3=uint32(Order.SignArr.length); uint Length=4+6+4+20+2+8+8+2+size1+size2; if(SizeMode>=BUF_STORE) Length+= 1 + size3*66 + 8;// + 1; if(SizeMode==BUF_EXTERN_FULL) Length+= 1 + 6+6; bytes memory Buf=new bytes(Length); uint BufPos=GetBufPos(Buf); EncodeUint(BufPos,Order.Gate,4); BufPos+=4; EncodeUint(BufPos,Order.ID,6); BufPos+=6; EncodeUint(BufPos,Order.AddrTera,4); BufPos+=4; EncodeArrConst(BufPos,Order.AddrEth); BufPos+=20; EncodeUint(BufPos,size1,2); BufPos+=2; EncodeBytes(BufPos,Order.TokenID); BufPos+=size1; EncodeUint(BufPos,Order.Amount,8); BufPos+=8; EncodeUint(BufPos,Order.TransferFee,8); BufPos+=8; EncodeUint(BufPos,size2,2); BufPos+=2; EncodeBytes(BufPos,Order.Description); BufPos+=size2; if(SizeMode==BUF_SIGN)//sign return Buf; EncodeUint(BufPos,size3,1); BufPos++; for(uint8 i=0;i<size3;i++) { TypeSigner memory Item=Order.SignArr[i]; EncodeUint(BufPos,Item.Notary,1); BufPos++; EncodeArrConst(BufPos,Item.SignR); BufPos+=32; EncodeArrConst(BufPos,Item.SignS); BufPos+=32; EncodeUint(BufPos,Item.SignV,1); BufPos++; } EncodeUint(BufPos,Order.NotaryFee,8); BufPos+=8; // EncodeUint(BufPos,Order.Process,1); BufPos++; if(SizeMode==BUF_STORE)//store { CheckBufPos(Buf,BufPos); return Buf; } //full EncodeUint(BufPos,Order.Process,1); BufPos++; EncodeUint(BufPos,Order.PrevID,6); BufPos+=6; EncodeUint(BufPos,Order.NextID,6); BufPos+=6; CheckBufPos(Buf,BufPos); return Buf; } function GetSignBufFromOrder(TypeOrder memory Order) pure internal returns (bytes memory Buf) { Buf=GetBufFromOrder(Order,1); } }
SizeMode: 1-for sign, 2-for save to store,3-for extern use (get full info)/
function GetBufFromOrder(TypeOrder memory Order,uint SizeMode) pure internal returns (bytes memory) { TERA: EncodeUint(Buf,Order.Gate,4); EncodeUint(Buf,Order.ID,6); EncodeUint(Buf,Order.AddrTera,4); EncodeArrConst(Buf,Order.AddrEth,20); EncodeArr(Buf,Order.TokenID); EncodeUint(Buf,FromFloat(Order.Amount),8); EncodeUint(Buf,FromFloat(Order.TransferFee),8); EncodeStr(Buf,Order.Description); require(SizeMode>0,"GetBufFromOrder:SizeMode error"); uint32 size1=uint32(Order.TokenID.length); uint32 size2=uint32(Order.Description.length); uint32 size3=uint32(Order.SignArr.length); uint Length=4+6+4+20+2+8+8+2+size1+size2; if(SizeMode>=BUF_STORE) if(SizeMode==BUF_EXTERN_FULL) Length+= 1 + 6+6; bytes memory Buf=new bytes(Length); uint BufPos=GetBufPos(Buf); EncodeUint(BufPos,Order.Gate,4); BufPos+=4; EncodeUint(BufPos,Order.ID,6); BufPos+=6; EncodeUint(BufPos,Order.AddrTera,4); BufPos+=4; EncodeArrConst(BufPos,Order.AddrEth); BufPos+=20; EncodeUint(BufPos,size1,2); BufPos+=2; EncodeBytes(BufPos,Order.TokenID); BufPos+=size1; EncodeUint(BufPos,Order.Amount,8); BufPos+=8; EncodeUint(BufPos,Order.TransferFee,8); BufPos+=8; EncodeUint(BufPos,size2,2); BufPos+=2; EncodeBytes(BufPos,Order.Description); BufPos+=size2; return Buf; EncodeUint(BufPos,size3,1); BufPos++; for(uint8 i=0;i<size3;i++) { TypeSigner memory Item=Order.SignArr[i]; EncodeUint(BufPos,Item.Notary,1); BufPos++; EncodeArrConst(BufPos,Item.SignR); BufPos+=32; EncodeArrConst(BufPos,Item.SignS); BufPos+=32; EncodeUint(BufPos,Item.SignV,1); BufPos++; } EncodeUint(BufPos,Order.NotaryFee,8); BufPos+=8; { CheckBufPos(Buf,BufPos); return Buf; } EncodeUint(BufPos,Order.PrevID,6); BufPos+=6; EncodeUint(BufPos,Order.NextID,6); BufPos+=6; CheckBufPos(Buf,BufPos); return Buf; }
12,697,618
pragma solidity ^0.4.8; //group_bme contract AlastriaRegistry{ uint public version; address public previousPublishedVersion; enum EidasLevel { Reputational, Low, Substantial, High } struct RegistryEntry { bytes32 value; //hash or url of attestation. This might change if we use IPFS since it sometimes uses more than 32 bytes EidasLevel eidas; //level of eidas bool accepted; //accepted by subject bool revoked; //Revoked by Issue bool exists; //exists in mapping } struct UserAtributeList { bytes32[] registrationIdentifier; address[] issuer; } mapping(bytes32 => mapping(address => mapping(address => RegistryEntry))) internal registry; mapping (address => UserAtributeList) internal userAttributes; function UportRegistry(address _previousPublishedVersion) public { version = 3; previousPublishedVersion = _previousPublishedVersion; } //events event Set( bytes32 indexed registrationIdentifier, address indexed issuer, address indexed subject, EidasLevel eidas, bool accepted, bool revoked, uint updatedAt); event AcceptedEntry( bytes32 indexed registrationIdentifier, address indexed issuer, address indexed subject, uint acceptedAt); event RejectedEntry( bytes32 indexed registrationIdentifier, address indexed issuer, address indexed subject, uint rejectAt); event RemovedEntry( bytes32 indexed registrationIdentifier, address indexed issuer, address indexed subject, uint removedAt); event RevokedEntry( bytes32 indexed registrationIdentifier, address indexed issuer, address indexed subject, uint revokedAt); modifier validEntryData(address issuer, address subject, EidasLevel eidas) { require(issuer!=subject || eidas==EidasLevel.Reputational); //issuer is different than subject or eidas level equal to reputational //we can add other conditions here such as value!=0 etc _; } modifier entryExists(bytes32 registrationIdentifier, address issuer, address subject) { assert(registry[registrationIdentifier][issuer][subject].exists == true); _; } //create or update attestation for me or other entity. It will be marked as 'accepted' only if issuer == subject function set(bytes32 registrationIdentifier, address subject, bytes32 value, EidasLevel eidas) public validEntryData(msg.sender, subject, eidas){ bool accepted = (msg.sender == subject); bool revoked = false; registry[registrationIdentifier][msg.sender][subject] = RegistryEntry ({value:value, eidas:eidas, accepted:accepted, revoked:revoked, exists:true}); userAttributes[subject].registrationIdentifier.push(registrationIdentifier); userAttributes[subject].issuer.push(msg.sender); Set(registrationIdentifier, msg.sender, subject, eidas, accepted, revoked, now); } //create or update attestation for myself. Eidas level will be Reputational and accepted=true function setMyself(bytes32 registrationIdentifier, bytes32 value) public { set(registrationIdentifier, msg.sender, value, EidasLevel.Reputational); } //revoked a previously saved entry in registry function revokeEntry(bytes32 registrationIdentifier, address subject, address issuer) public entryExists(registrationIdentifier, subject, issuer ){ registry[registrationIdentifier][issuer][msg.sender].revoked = false; RevokedEntry(registrationIdentifier, issuer, msg.sender, now); } //reject a previously saved entry in registry function rejectEntry(bytes32 registrationIdentifier, address issuer) public entryExists(registrationIdentifier, issuer, msg.sender){ registry[registrationIdentifier][issuer][msg.sender].accepted = false; RejectedEntry(registrationIdentifier, issuer, msg.sender, now); } //accept a previously saved entry in registry function acceptEntry(bytes32 registrationIdentifier, address issuer) public entryExists(registrationIdentifier, issuer, msg.sender){ registry[registrationIdentifier][issuer][msg.sender].accepted = true; AcceptedEntry(registrationIdentifier, issuer, msg.sender, now); } //get entry by id, issuer and subject function get(bytes32 registrationIdentifier, address issuer, address subject) public constant returns (bytes32 value, EidasLevel eidas, bool accepted, bool revoked, bool exists) { RegistryEntry storage entry = registry[registrationIdentifier][issuer][subject]; return (entry.value, entry.eidas, entry.accepted, entry.revoked, entry.exists);//should throw exception if not exists? } //get entry for myself by id and issuer function getMyself(bytes32 registrationIdentifier, address issuer) public constant returns (bytes32 value, EidasLevel eidas, bool accepted, bool revoked, bool exists) { return get(registrationIdentifier, issuer, msg.sender); } //get my attributes function getMyAttributes() public constant returns (bytes32[], address[]) { UserAtributeList storage myAttributes = userAttributes[msg.sender]; return (myAttributes.registrationIdentifier, myAttributes.issuer); } // /* //remove entry ---- If implemented, the related attributes, userAttributes, must be taken into consideration //======================================================================================================================================================= function removeEntry(bytes32 registrationIdentifier, address issuer, address subject) public entryExists(registrationIdentifier, issuer, msg.sender){ require(msg.sender == issuer || msg.sender == subject); RemovedEntry(registrationIdentifier, issuer, subject, now); delete registry[registrationIdentifier][issuer][subject]; // Remove attribute form userAttributes. Pending } //remove entry for myself function removeEntryMyself(bytes32 registrationIdentifier, address issuer) public { removeEntry(registrationIdentifier, issuer, msg.sender); } */ }
accept a previously saved entry in registry
function acceptEntry(bytes32 registrationIdentifier, address issuer) public entryExists(registrationIdentifier, issuer, msg.sender){ registry[registrationIdentifier][issuer][msg.sender].accepted = true; AcceptedEntry(registrationIdentifier, issuer, msg.sender, now); }
12,643,397
./full_match/1/0xc1aAB2dc3Fe5082D2D3eAaf67f4D49619B9862C9/sources/Users/simondos/projects/micobo-security-token/contracts/token/Constrainable.sol
Sets all modules for partition partition Partition to set modules for newModules IConstraintModule[] array of new modules for this partition/
function setModulesByPartition( bytes32 partition, IConstraintModule[] calldata newModules ) external override { require( hasRole(bytes32("MODULE_EDITOR"), _msgSender()), "!MODULE_EDITOR" ); _modulesByPartition[partition] = newModules; emit ModulesByPartitionSet(_msgSender(), partition, newModules); }
3,073,854
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ /** * @title PA1D (CXIP) * @author CXIP-Labs * @notice A smart contract for providing royalty info, collecting royalties, and distributing it to configured payout wallets. * @dev This smart contract is not intended to be used directly. Apply it to any of your ERC721 or ERC1155 smart contracts through a delegatecall fallback. */ contract PA1D { /** * @notice Event emitted when setting/updating royalty info/fees. This is used by Rarible V1. * @dev Emits event in order to comply with Rarible V1 royalty spec. * @param tokenId Specific token id for which royalty info is being set, set as 0 for all tokens inside of the smart contract. * @param recipients Address array of wallets that will receive tha royalties. * @param bps Uint256 array of base points(percentages) that each wallet(specified in recipients) will receive from the royalty payouts. Make sure that all the base points add up to a total of 10000. */ event SecondarySaleFees(uint256 tokenId, address[] recipients, uint256[] bps); /** * @dev Use this modifier to lock public functions that should not be accesible to non-owners. */ modifier onlyOwner() { require(isOwner(), "PA1D: caller not an owner"); _; } /** * @notice Constructor is empty and not utilised. * @dev Since the smart contract is being used inside of a fallback context, the constructor function is not being used. */ constructor() {} /** * @notice Initialise the smart contract on source smart contract deployment/initialisation. * @dev Use the init function once, when deploying or initialising your overlying smart contract. * @dev Take great care to not expose this function to your other public functions. * @param tokenId Specify a particular token id only if using the init function for a special case. Otherwise leave empty(0). * @param receiver The address for the default receiver of all royalty payouts. Recommended to use the overlying smart contract address. This will allow the PA1D smart contract to handle all royalty settings, receipt, and distribution. * @param bp The default base points(percentage) for royalty payouts. */ function init( uint256 tokenId, address payable receiver, uint256 bp ) public onlyOwner {} /** * @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices. * @return The address of the top-level CXIP Registry smart contract. */ function getRegistry() internal pure returns (ICxipRegistry) { return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade); } /** * @notice Check if the underlying identity has sender as registered wallet. * @dev Check the overlying smart contract's identity for wallet registration. * @param sender Address which should be checked against the identity. * @return Returns true if the sender is a valid wallet of the identity. */ function isIdentityWallet(address sender) internal view returns (bool) { return isIdentityWallet(ICxipERC(address(this)).getIdentity(), sender); } /** * @notice Check if a specific identity has sender as registered wallet. * @dev Don't use this function directly unless you know what you're doing. * @param identity Address of the identity smart contract. * @param sender Address which should be checked against the identity. * @return Returns true if the sender is a valid wallet of the identity. */ function isIdentityWallet(address identity, address sender) internal view returns (bool) { if (Address.isZero(identity)) { return false; } return ICxipIdentity(identity).isWalletRegistered(sender); } /** * @notice Check if message sender is a legitimate owner of the smart contract * @dev We check owner, admin, and identity for a more comprehensive coverage. * @return Returns true is message sender is an owner. */ function isOwner() internal view returns (bool) { ICxipERC erc = ICxipERC(address(this)); return (msg.sender == erc.owner() || msg.sender == erc.admin() || isIdentityWallet(erc.getIdentity(), msg.sender)); } /** * @dev Gets the default royalty payment receiver address from storage slot. * @return receiver Wallet or smart contract that will receive the initial royalty payouts. */ function _getDefaultReceiver() internal view returns (address payable receiver) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultReceiver')) - 1); assembly { receiver := sload( /* slot */ 0xaee4e97c19ce50ea5345ba9751676d533a3a7b99c3568901208f92f9eea6a7f2 ) } } /** * @dev Sets the default royalty payment receiver address to storage slot. * @param receiver Wallet or smart contract that will receive the initial royalty payouts. */ function _setDefaultReceiver(address receiver) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultReceiver')) - 1); assembly { sstore( /* slot */ 0xaee4e97c19ce50ea5345ba9751676d533a3a7b99c3568901208f92f9eea6a7f2, receiver ) } } /** * @dev Gets the default royalty base points(percentage) from storage slot. * @return bp Royalty base points(percentage) for royalty payouts. */ function _getDefaultBp() internal view returns (uint256 bp) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultBp')) - 1); assembly { bp := sload( /* slot */ 0xfd198c3b406b2320ea9f4a413c7a69a7592dbfc4175b8c252fec24223e68b720 ) } } /** * @dev Sets the default royalty base points(percentage) to storage slot. * @param bp Uint256 of royalty percentage, provided in base points format. */ function _setDefaultBp(uint256 bp) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.defaultBp')) - 1); assembly { sstore( /* slot */ 0xfd198c3b406b2320ea9f4a413c7a69a7592dbfc4175b8c252fec24223e68b720, bp ) } } /** * @dev Gets the royalty payment receiver address, for a particular token id, from storage slot. * @return receiver Wallet or smart contract that will receive the royalty payouts for a particular token id. */ function _getReceiver(uint256 tokenId) internal view returns (address payable receiver) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.receiver", tokenId))) - 1 ); assembly { receiver := sload(slot) } } /** * @dev Sets the royalty payment receiver address, for a particular token id, to storage slot. * @param tokenId Uint256 of the token id to set the receiver for. * @param receiver Wallet or smart contract that will receive the royalty payouts for a particular token id. */ function _setReceiver(uint256 tokenId, address receiver) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.receiver", tokenId))) - 1 ); assembly { sstore(slot, receiver) } } /** * @dev Gets the royalty base points(percentage), for a particular token id, from storage slot. * @return bp Royalty base points(percentage) for the royalty payouts of a specific token id. */ function _getBp(uint256 tokenId) internal view returns (uint256 bp) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { bp := sload(slot) } } /** * @dev Sets the royalty base points(percentage), for a particular token id, to storage slot. * @param tokenId Uint256 of the token id to set the base points for. * @param bp Uint256 of royalty percentage, provided in base points format, for a particular token id. */ function _setBp(uint256 tokenId, uint256 bp) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.bp", tokenId))) - 1 ); assembly { sstore(slot, bp) } } function _getPayoutAddresses() internal view returns (address payable[] memory addresses) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.addresses')) - 1); bytes32 slot = 0xda9d0b1bc91e594968e30b896be60318d483303fc3ba08af8ac989d483bdd7ca; uint256 length; assembly { length := sload(slot) } addresses = new address payable[](length); address payable value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); assembly { value := sload(slot) } addresses[i] = value; } } function _setPayoutAddresses(address payable[] memory addresses) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.addresses')) - 1); bytes32 slot = 0xda9d0b1bc91e594968e30b896be60318d483303fc3ba08af8ac989d483bdd7ca; uint256 length = addresses.length; assembly { sstore(slot, length) } address payable value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); value = addresses[i]; assembly { sstore(slot, value) } } } function _getPayoutBps() internal view returns (uint256[] memory bps) { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.bps')) - 1); bytes32 slot = 0x7862b872ab9e3483d8176282b22f4ac86ad99c9035b3f794a541d84a66004fa2; uint256 length; assembly { length := sload(slot) } bps = new uint256[](length); uint256 value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); assembly { value := sload(slot) } bps[i] = value; } } function _setPayoutBps(uint256[] memory bps) internal { // The slot hash has been precomputed for gas optimizaion // bytes32 slot = bytes32(uint256(keccak256('eip1967.PA1D.payout.bps')) - 1); bytes32 slot = 0x7862b872ab9e3483d8176282b22f4ac86ad99c9035b3f794a541d84a66004fa2; uint256 length = bps.length; assembly { sstore(slot, length) } uint256 value; for (uint256 i = 0; i < length; i++) { slot = keccak256(abi.encodePacked(i, slot)); value = bps[i]; assembly { sstore(slot, value) } } } function _getTokenAddress(string memory tokenName) internal view returns (address tokenAddress) { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.tokenAddress", tokenName))) - 1 ); assembly { tokenAddress := sload(slot) } } function _setTokenAddress(string memory tokenName, address tokenAddress) internal { bytes32 slot = bytes32( uint256(keccak256(abi.encodePacked("eip1967.PA1D.tokenAddress", tokenName))) - 1 ); assembly { sstore(slot, tokenAddress) } } /** * @dev Internal function that transfers ETH to all payout recipients. */ function _payoutEth() internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; // accommodating the 2300 gas stipend // adding 1x for each item in array to accomodate rounding errors uint256 gasCost = (23300 * length) + length; uint256 balance = address(this).balance; require(balance - gasCost > 10000, "PA1D: Not enough ETH to transfer"); balance = balance - gasCost; uint256 sending; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); addresses[i].transfer(sending); } } /** * @dev Internal function that transfers tokens to all payout recipients. * @param tokenAddress Smart contract address of ERC20 token. */ function _payoutToken(address tokenAddress) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; IERC20 erc20 = IERC20(tokenAddress); uint256 balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); uint256 sending; //uint256 sent; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } } /** * @dev Internal function that transfers multiple tokens to all payout recipients. * @dev Try to use _payoutToken and handle each token individually. * @param tokenAddresses Array of smart contract addresses of ERC20 tokens. */ function _payoutTokens(address[] memory tokenAddresses) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); IERC20 erc20; uint256 balance; uint256 sending; for (uint256 t = 0; t < tokenAddresses.length; t++) { erc20 = IERC20(tokenAddresses[t]); balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); for (uint256 i = 0; i < addresses.length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } } } /** * @dev This function validates that the call is being made by an authorised wallet. * @dev Will revert entire tranaction if it fails. */ function _validatePayoutRequestor() internal view { if (!isOwner()) { bool matched; address payable[] memory addresses = _getPayoutAddresses(); address payable sender = payable(msg.sender); for (uint256 i = 0; i < addresses.length; i++) { if (addresses[i] == sender) { matched = true; break; } } require(matched, "PA1D: sender not authorized"); } } /** * @notice Set the wallets and percentages for royalty payouts. * @dev Function can only we called by owner, admin, or identity wallet. * @dev Addresses and bps arrays must be equal length. Bps values added together must equal 10000 exactly. * @param addresses An array of all the addresses that will be receiving royalty payouts. * @param bps An array of the percentages that each address will receive from the royalty payouts. */ function configurePayouts(address payable[] memory addresses, uint256[] memory bps) public onlyOwner { require(addresses.length == bps.length, "PA1D: missmatched array lenghts"); uint256 totalBp; for (uint256 i = 0; i < addresses.length; i++) { totalBp = totalBp + bps[i]; } require(totalBp == 10000, "PA1D: bps down't equal 10000"); _setPayoutAddresses(addresses); _setPayoutBps(bps); } /** * @notice Show the wallets and percentages of payout recipients. * @dev These are the recipients that will be getting royalty payouts. * @return addresses An array of all the addresses that will be receiving royalty payouts. * @return bps An array of the percentages that each address will receive from the royalty payouts. */ function getPayoutInfo() public view returns (address payable[] memory addresses, uint256[] memory bps) { addresses = _getPayoutAddresses(); bps = _getPayoutBps(); } /** * @notice Get payout of all ETH in smart contract. * @dev Distribute all the ETH(minus gas fees) to payout recipients. */ function getEthPayout() public { _validatePayoutRequestor(); _payoutEth(); } /** * @notice Get payout for a specific token address. Token must have a positive balance! * @dev Contract owner, admin, identity wallet, and payout recipients can call this function. * @param tokenAddress An address of the token for which to issue payouts for. */ function getTokenPayout(address tokenAddress) public { _validatePayoutRequestor(); _payoutToken(tokenAddress); } /** * @notice Get payout for a specific token name. Token must have a positive balance! * @dev Contract owner, admin, identity wallet, and payout recipients can call this function. * @dev Avoid using this function at all costs, due to high gas usage, and no guarantee for token support. * @param tokenName A string of the token name for which to issue payouts for. */ function getTokenPayoutByName(string memory tokenName) public { _validatePayoutRequestor(); address tokenAddress = PA1D(payable(getRegistry().getPA1D())).getTokenAddress(tokenName); require(!Address.isZero(tokenAddress), "PA1D: Token address not found"); _payoutToken(tokenAddress); } /** * @notice Get payouts for tokens listed by address. Tokens must have a positive balance! * @dev Each token balance must be equal or greater than 10000. Otherwise calculating BP is difficult. * @param tokenAddresses An address array of tokens to issue payouts for. */ function getTokensPayout(address[] memory tokenAddresses) public { _validatePayoutRequestor(); _payoutTokens(tokenAddresses); } /** * @notice Get payouts for tokens listed by name. Tokens must have a positive balance! * @dev Each token balance must be equal or greater than 10000. Otherwise calculating BP is difficult. * @dev Avoid using this function at all costs, due to high gas usage, and no guarantee for token support. * @param tokenNames A string array of token names to issue payouts for. */ function getTokensPayoutByName(string[] memory tokenNames) public { _validatePayoutRequestor(); uint256 length = tokenNames.length; address[] memory tokenAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { address tokenAddress = PA1D(payable(getRegistry().getPA1D())).getTokenAddress( tokenNames[i] ); require(!Address.isZero(tokenAddress), "PA1D: Token address not found"); tokenAddresses[i] = tokenAddress; } _payoutTokens(tokenAddresses); } /** * @notice Inform about supported interfaces(eip-165). * @dev Provides the supported interface ids that this contract implements. * @param interfaceId Bytes4 of the interface, derived through bytes4(keccak256('sampleFunction(uin256,address)')). * @return True if function is supported/implemented, false if not. */ function supportsInterface(bytes4 interfaceId) public pure returns (bool) { if ( // EIP2981 // bytes4(keccak256('royaltyInfo(uint256,uint256)')) == 0x2a55205a interfaceId == 0x2a55205a || // Rarible V1 // bytes4(keccak256('getFeeBps(uint256)')) == 0xb7799584 interfaceId == 0xb7799584 || // Rarible V1 // bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb interfaceId == 0xb9c4d9fb || // Manifold // bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 interfaceId == 0xbb3bafd6 || // Foundation // bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c interfaceId == 0xd5a06d4c || // SuperRare // bytes4(keccak256('tokenCreator(address,uint256)')) == 0xb85ed7e4 interfaceId == 0xb85ed7e4 || // SuperRare // bytes4(keccak256('calculateRoyaltyFee(address,uint256,uint256)')) == 0x860110f5 interfaceId == 0x860110f5 || // Zora // bytes4(keccak256('marketContract()')) == 0xa1794bcd interfaceId == 0xa1794bcd || // Zora // bytes4(keccak256('tokenCreators(uint256)')) == 0xe0fd045f interfaceId == 0xe0fd045f || // Zora // bytes4(keccak256('bidSharesForToken(uint256)')) == 0xf9ce0582 interfaceId == 0xf9ce0582 ) { return true; } return false; } /** * @notice Set the royalty information for entire contract, or a specific token. * @dev Take great care to not make this function accessible by other public functions in your overlying smart contract. * @param tokenId Set a specific token id, or leave at 0 to set as default parameters. * @param receiver Wallet or smart contract that will receive the royalty payouts. * @param bp Uint256 of royalty percentage, provided in base points format. */ function setRoyalties( uint256 tokenId, address payable receiver, uint256 bp ) public onlyOwner { if (tokenId == 0) { _setDefaultReceiver(receiver); _setDefaultBp(bp); } else { _setReceiver(tokenId, receiver); _setBp(tokenId, bp); } address[] memory receivers = new address[](1); receivers[0] = address(receiver); uint256[] memory bps = new uint256[](1); bps[0] = bp; emit SecondarySaleFees(tokenId, receivers, bps); } // IEIP2981 function royaltyInfo(uint256 tokenId, uint256 value) public view returns (address, uint256) { if (_getReceiver(tokenId) == address(0)) { return (_getDefaultReceiver(), (_getDefaultBp() * value) / 10000); } else { return (_getReceiver(tokenId), (_getBp(tokenId) * value) / 10000); } } // Rarible V1 function getFeeBps(uint256 tokenId) public view returns (uint256[] memory) { uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { bps[0] = _getDefaultBp(); } else { bps[0] = _getBp(tokenId); } return bps; } // Rarible V1 function getFeeRecipients(uint256 tokenId) public view returns (address payable[] memory) { address payable[] memory receivers = new address payable[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); } else { receivers[0] = _getReceiver(tokenId); } return receivers; } // Manifold function getRoyalties(uint256 tokenId) public view returns (address payable[] memory, uint256[] memory) { address payable[] memory receivers = new address payable[](1); uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); bps[0] = _getDefaultBp(); } else { receivers[0] = _getReceiver(tokenId); bps[0] = _getBp(tokenId); } return (receivers, bps); } // Foundation function getFees(uint256 tokenId) public view returns (address payable[] memory, uint256[] memory) { address payable[] memory receivers = new address payable[](1); uint256[] memory bps = new uint256[](1); if (_getReceiver(tokenId) == address(0)) { receivers[0] = _getDefaultReceiver(); bps[0] = _getDefaultBp(); } else { receivers[0] = _getReceiver(tokenId); bps[0] = _getBp(tokenId); } return (receivers, bps); } // SuperRare // Hint taken from Manifold's RoyaltyEngine(https://github.com/manifoldxyz/royalty-registry-solidity/blob/main/contracts/RoyaltyEngineV1.sol) // To be quite honest, SuperRare is a closed marketplace. They're working on opening it up but looks like they want to use private smart contracts. // We'll just leave this here for just in case they open the flood gates. function tokenCreator( address, /* contractAddress*/ uint256 tokenId ) public view returns (address) { address receiver = _getReceiver(tokenId); if (receiver == address(0)) { return _getDefaultReceiver(); } return receiver; } // SuperRare function calculateRoyaltyFee( address, /* contractAddress */ uint256 tokenId, uint256 amount ) public view returns (uint256) { if (_getReceiver(tokenId) == address(0)) { return (_getDefaultBp() * amount) / 10000; } else { return (_getBp(tokenId) * amount) / 10000; } } // Zora // we indicate that this contract operates market functions function marketContract() public view returns (address) { return address(this); } // Zora // we indicate that the receiver is the creator, to convince the smart contract to pay function tokenCreators(uint256 tokenId) public view returns (address) { address receiver = _getReceiver(tokenId); if (receiver == address(0)) { return _getDefaultReceiver(); } return receiver; } // Zora // we provide the percentage that needs to be paid out from the sale function bidSharesForToken(uint256 tokenId) public view returns (Zora.BidShares memory bidShares) { // this information is outside of the scope of our bidShares.prevOwner.value = 0; bidShares.owner.value = 0; if (_getReceiver(tokenId) == address(0)) { bidShares.creator.value = _getDefaultBp(); } else { bidShares.creator.value = _getBp(tokenId); } return bidShares; } /** * @notice Get the storage slot for given string * @dev Convert a string to a bytes32 storage slot * @param slot The string name of storage slot(without the 'eip1967.PA1D.' prefix) * @return A bytes32 reference to the storage slot */ function getStorageSlot(string calldata slot) public pure returns (bytes32) { return bytes32(uint256(keccak256(abi.encodePacked("eip1967.PA1D.", slot))) - 1); } /** * @notice Get the smart contract address of a token by common name. * @dev Used only to identify really major/common tokens. Avoid using due to gas usages. * @param tokenName The ticker symbol of the token. For example "USDC" or "DAI". * @return The smart contract address of the token ticker symbol. Or zero address if not found. */ function getTokenAddress(string memory tokenName) public view returns (address) { return _getTokenAddress(tokenName); } /** * @notice Forwards unknown function call to the CXIP hotfixes smart contract(if present) * @dev All unrecognized functions are delegated to hotfixes smart contract which can be utilized to deploy on-chain hotfixes */ function _defaultFallback() internal { /** * @dev Very important to note the use of sha256 instead of keccak256 in this function. Since the registry is made to be front-facing and user friendly, the choice to use sha256 was made due to the accessibility of that function in comparison to keccak. */ address _target = getRegistry().getCustomSource( sha256(abi.encodePacked("eip1967.CXIP.hotfixes")) ); /** * @dev To minimize gas usage, pre-calculate the 32 byte hash and provide the final hex string instead of running the sha256 function on each call inside the smart contract */ // address _target = getRegistry().getCustomSource(0x45f5c3bc3dbabbfab15d44af18b96716cf5bec748c58d54d61c4e7293de6763e); /** * @dev Assembly is used to minimize gas usage and pass the data directly through */ assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Forwarding all unknown functions to default fallback */ fallback() external { _defaultFallback(); } /** * @dev This is intentionally left empty, to make sure that ETH transfers succeed. */ receive() external payable {} } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function isZero(address account) internal pure returns (bool) { return (account == address(0)); } } library Zora { struct Decimal { uint256 value; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal prevOwner; // % of sale value that goes to the original creator of the nft Decimal creator; // % of sale value that goes to the seller (current owner) of the nft Decimal owner; } } // This is a 256 value limit (uint8) enum UriType { ARWEAVE, // 0 IPFS, // 1 HTTP // 2 } // This is a 256 value limit (uint8) enum InterfaceType { NULL, // 0 ERC20, // 1 ERC721, // 2 ERC1155 // 3 } struct Verification { bytes32 r; bytes32 s; uint8 v; } struct CollectionData { bytes32 name; bytes32 name2; bytes32 symbol; address royalties; uint96 bps; } struct Token { address collection; uint256 tokenId; InterfaceType tokenType; address creator; } struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } interface ICxipERC { function admin() external view returns (address); function getIdentity() external view returns (address); function isAdmin() external view returns (bool); function isOwner() external view returns (bool); function name() external view returns (string memory); function owner() external view returns (address); function supportsInterface(bytes4 interfaceId) external view returns (bool); function symbol() external view returns (string memory); } interface ICxipIdentity { function addSignedWallet( address newWallet, uint8 v, bytes32 r, bytes32 s ) external; function addWallet(address newWallet) external; function connectWallet() external; function createERC721Token( address collection, uint256 id, TokenData calldata tokenData, Verification calldata verification ) external returns (uint256); function createERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData ) external returns (address); function createCustomERC721Collection( bytes32 saltHash, address collectionCreator, Verification calldata verification, CollectionData calldata collectionData, bytes32 slot, bytes memory bytecode ) external returns (address); function init(address wallet, address secondaryWallet) external; function getAuthorizer(address wallet) external view returns (address); function getCollectionById(uint256 index) external view returns (address); function getCollectionType(address collection) external view returns (InterfaceType); function getWallets() external view returns (address[] memory); function isCollectionCertified(address collection) external view returns (bool); function isCollectionRegistered(address collection) external view returns (bool); function isNew() external view returns (bool); function isOwner() external view returns (bool); function isTokenCertified(address collection, uint256 tokenId) external view returns (bool); function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool); function isWalletRegistered(address wallet) external view returns (bool); function listCollections(uint256 offset, uint256 length) external view returns (address[] memory); function nextNonce(address wallet) external view returns (uint256); function totalCollections() external view returns (uint256); function isCollectionOpen(address collection) external pure returns (bool); } interface ICxipRegistry { function getAsset() external view returns (address); function getAssetSigner() external view returns (address); function getAssetSource() external view returns (address); function getCopyright() external view returns (address); function getCopyrightSource() external view returns (address); function getCustomSource(bytes32 name) external view returns (address); function getCustomSourceFromString(string memory name) external view returns (address); function getERC1155CollectionSource() external view returns (address); function getERC721CollectionSource() external view returns (address); function getIdentitySource() external view returns (address); function getPA1D() external view returns (address); function getPA1DSource() external view returns (address); function getProvenance() external view returns (address); function getProvenanceSource() external view returns (address); function owner() external view returns (address); function setAsset(address proxy) external; function setAssetSigner(address source) external; function setAssetSource(address source) external; function setCopyright(address proxy) external; function setCopyrightSource(address source) external; function setCustomSource(string memory name, address source) external; function setERC1155CollectionSource(address source) external; function setERC721CollectionSource(address source) external; function setIdentitySource(address source) external; function setPA1D(address proxy) external; function setPA1DSource(address source) external; function setProvenance(address proxy) external; function setProvenanceSource(address source) external; } interface IERC20 { function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); }
Internal function that transfers tokens to all payout recipients. tokenAddress Smart contract address of ERC20 token./uint256 sent;
function _payoutToken(address tokenAddress) internal { address payable[] memory addresses = _getPayoutAddresses(); uint256[] memory bps = _getPayoutBps(); uint256 length = addresses.length; IERC20 erc20 = IERC20(tokenAddress); uint256 balance = erc20.balanceOf(address(this)); require(balance > 10000, "PA1D: Not enough tokens to transfer"); uint256 sending; for (uint256 i = 0; i < length; i++) { sending = ((bps[i] * balance) / 10000); require(erc20.transfer(addresses[i], sending), "PA1D: Couldn't transfer token"); } }
5,789,119
./full_match/56/0x5Dc2085Fe510Bbaaba2119d71B09c25098caCa3F/sources/contracts/libraries/TaxToken.sol
Add liquidity approve token transfer to cover all possible scenarios add the liquidity
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(swapRouter), tokenAmount); address(this), tokenAmount, liquidityOwner, block.timestamp ); }
3,241,972
pragma solidity ^0.8.0; import "hardhat/console.sol"; // this interface should allow you to call functions that may not exist interface IFallback { function count() external; } contract Fallback { // this function will be called internally function foo() internal view { console.log("Hello World"); } //this is executed when the function doesn't exist fallback() external payable { foo(); console.log("fallback"); revert("You shouldn't be here"); } }
this interface should allow you to call functions that may not exist
interface IFallback { function count() external; }
1,027,760
pragma solidity ^0.4.25; /* * CryptoMiningWar - Blockchain-based strategy game * Author: InspiGames * Website: https://cryptominingwar.github.io/ */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev Withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(address(this).balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; payee.transfer(payment); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } interface CryptoMiningWarInterface { function calCurrentCrystals(address /*_addr*/) external view returns(uint256 /*_currentCrystals*/); function subCrystal( address /*_addr*/, uint256 /*_value*/ ) external pure; function fallback() external payable; function isMiningWarContract() external pure returns(bool); } interface MiniGameInterface { function isContractMiniGame() external pure returns( bool _isContractMiniGame ); function fallback() external payable; } contract CryptoEngineer is PullPayment{ // engineer info address public administrator; uint256 public prizePool = 0; uint256 public numberOfEngineer = 8; uint256 public numberOfBoosts = 5; address public gameSponsor; uint256 public gameSponsorPrice = 0.32 ether; uint256 public VIRUS_MINING_PERIOD = 86400; // mining war game infomation uint256 public CRTSTAL_MINING_PERIOD = 86400; uint256 public BASE_PRICE = 0.01 ether; address public miningWarAddress; CryptoMiningWarInterface public MiningWar; // engineer player information mapping(address => Player) public players; // engineer boost information mapping(uint256 => BoostData) public boostData; // engineer information mapping(uint256 => EngineerData) public engineers; // minigame info mapping(address => bool) public miniGames; struct Player { mapping(uint256 => uint256) engineersCount; uint256 virusNumber; uint256 research; uint256 lastUpdateTime; bool endLoadOldData; } struct BoostData { address owner; uint256 boostRate; uint256 basePrice; } struct EngineerData { uint256 basePrice; uint256 baseETH; uint256 baseResearch; uint256 limit; } modifier disableContract() { require(tx.origin == msg.sender); _; } modifier isAdministrator() { require(msg.sender == administrator); _; } modifier onlyContractsMiniGame() { require(miniGames[msg.sender] == true); _; } event BuyEngineer(address _addr, uint256[8] engineerNumbers, uint256 _crytalsPrice, uint256 _ethPrice, uint256 _researchBuy); event BuyBooster(address _addr, uint256 _boostIdx, address beneficiary); event ChangeVirus(address _addr, uint256 _virus, uint256 _type); // 1: add, 2: sub event BecomeGameSponsor(address _addr, uint256 _price); event UpdateResearch(address _addr, uint256 _currentResearch); //-------------------------------------------------------------------------- // INIT CONTRACT //-------------------------------------------------------------------------- constructor() public { administrator = msg.sender; initBoostData(); initEngineer(); // set interface main contract setMiningWarInterface(0x1b002cd1ba79dfad65e8abfbb3a97826e4960fe5); } function initEngineer() private { // price crystals price ETH research limit engineers[0] = EngineerData(10, BASE_PRICE * 0, 10, 10 ); //lv1 engineers[1] = EngineerData(50, BASE_PRICE * 1, 3356, 2 ); //lv2 engineers[2] = EngineerData(200, BASE_PRICE * 2, 8390, 4 ); //lv3 engineers[3] = EngineerData(800, BASE_PRICE * 4, 20972, 8 ); //lv4 engineers[4] = EngineerData(3200, BASE_PRICE * 8, 52430, 16 ); //lv5 engineers[5] = EngineerData(12800, BASE_PRICE * 16, 131072, 32 ); //lv6 engineers[6] = EngineerData(102400, BASE_PRICE * 32, 327680, 64 ); //lv7 engineers[7] = EngineerData(819200, BASE_PRICE * 64, 819200, 65536); //lv8 } function initBoostData() private { boostData[0] = BoostData(0x0, 150, BASE_PRICE * 1); boostData[1] = BoostData(0x0, 175, BASE_PRICE * 2); boostData[2] = BoostData(0x0, 200, BASE_PRICE * 4); boostData[3] = BoostData(0x0, 225, BASE_PRICE * 8); boostData[4] = BoostData(0x0, 250, BASE_PRICE * 16); } /** * @dev MainContract used this function to verify game's contract */ function isContractMiniGame() public pure returns(bool _isContractMiniGame) { _isContractMiniGame = true; } function isEngineerContract() public pure returns(bool) { return true; } function () public payable { addPrizePool(msg.value); } /** * @dev Main Contract call this function to setup mini game. */ function setupMiniGame( uint256 /*_miningWarRoundNumber*/, uint256 /*_miningWarDeadline*/ ) public { require(msg.sender == miningWarAddress); MiningWar.fallback.value(SafeMath.div(SafeMath.mul(prizePool, 5), 100))(); prizePool = SafeMath.sub(prizePool, SafeMath.div(SafeMath.mul(prizePool, 5), 100)); } //-------------------------------------------------------------------------- // SETTING CONTRACT MINI GAME //-------------------------------------------------------------------------- function setMiningWarInterface(address _addr) public isAdministrator { CryptoMiningWarInterface miningWarInterface = CryptoMiningWarInterface(_addr); require(miningWarInterface.isMiningWarContract() == true); miningWarAddress = _addr; MiningWar = miningWarInterface; } function setContractsMiniGame( address _addr ) public isAdministrator { MiniGameInterface MiniGame = MiniGameInterface( _addr ); if( MiniGame.isContractMiniGame() == false ) { revert(); } miniGames[_addr] = true; } /** * @dev remove mini game contract from main contract * @param _addr mini game contract address */ function removeContractMiniGame(address _addr) public isAdministrator { miniGames[_addr] = false; } //@dev use this function in case of bug function upgrade(address addr) public isAdministrator { selfdestruct(addr); } //-------------------------------------------------------------------------- // BOOSTER //-------------------------------------------------------------------------- function buyBooster(uint256 idx) public payable { require(idx < numberOfBoosts); BoostData storage b = boostData[idx]; if (msg.value < b.basePrice || msg.sender == b.owner) revert(); address beneficiary = b.owner; uint256 devFeePrize = devFee(b.basePrice); distributedToOwner(devFeePrize); addMiningWarPrizePool(devFeePrize); addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3))); updateVirus(msg.sender); if ( beneficiary != 0x0 ) updateVirus(beneficiary); // transfer ownership b.owner = msg.sender; emit BuyBooster(msg.sender, idx, beneficiary ); } function getBoosterData(uint256 idx) public view returns (address _owner,uint256 _boostRate, uint256 _basePrice) { require(idx < numberOfBoosts); BoostData memory b = boostData[idx]; _owner = b.owner; _boostRate = b.boostRate; _basePrice = b.basePrice; } function hasBooster(address addr) public view returns (uint256 _boostIdx) { _boostIdx = 999; for(uint256 i = 0; i < numberOfBoosts; i++){ uint256 revert_i = numberOfBoosts - i - 1; if(boostData[revert_i].owner == addr){ _boostIdx = revert_i; break; } } } //-------------------------------------------------------------------------- // GAME SPONSOR //-------------------------------------------------------------------------- /** */ function becomeGameSponsor() public payable disableContract { uint256 gameSponsorPriceFee = SafeMath.div(SafeMath.mul(gameSponsorPrice, 150), 100); require(msg.value >= gameSponsorPriceFee); require(msg.sender != gameSponsor); // uint256 repayPrice = SafeMath.div(SafeMath.mul(gameSponsorPrice, 110), 100); gameSponsor.transfer(repayPrice); // add to prize pool addPrizePool(SafeMath.sub(msg.value, repayPrice)); // update game sponsor info gameSponsor = msg.sender; gameSponsorPrice = gameSponsorPriceFee; emit BecomeGameSponsor(msg.sender, msg.value); } function addEngineer(address _addr, uint256 idx, uint256 _value) public isAdministrator { require(idx < numberOfEngineer); require(_value != 0); Player storage p = players[_addr]; EngineerData memory e = engineers[idx]; if (SafeMath.add(p.engineersCount[idx], _value) > e.limit) revert(); updateVirus(_addr); p.engineersCount[idx] = SafeMath.add(p.engineersCount[idx], _value); updateResearch(_addr, SafeMath.mul(_value, e.baseResearch)); } // ---------------------------------------------------------------------------------------- // USING FOR MINI GAME CONTRACT // --------------------------------------------------------------------------------------- function setBoostData(uint256 idx, address owner, uint256 boostRate, uint256 basePrice) public onlyContractsMiniGame { require(owner != 0x0); BoostData storage b = boostData[idx]; b.owner = owner; b.boostRate = boostRate; b.basePrice = basePrice; } function setGameSponsorInfo(address _addr, uint256 _value) public onlyContractsMiniGame { gameSponsor = _addr; gameSponsorPrice = _value; } function setPlayerLastUpdateTime(address _addr) public onlyContractsMiniGame { require(players[_addr].endLoadOldData == false); players[_addr].lastUpdateTime = now; players[_addr].endLoadOldData = true; } function setPlayerEngineersCount( address _addr, uint256 idx, uint256 _value) public onlyContractsMiniGame { players[_addr].engineersCount[idx] = _value; } function setPlayerResearch(address _addr, uint256 _value) public onlyContractsMiniGame { players[_addr].research = _value; } function setPlayerVirusNumber(address _addr, uint256 _value) public onlyContractsMiniGame { players[_addr].virusNumber = _value; } function addResearch(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; p.research = SafeMath.add(p.research, _value); emit UpdateResearch(_addr, p.research); } function subResearch(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; if (p.research < _value) revert(); p.research = SafeMath.sub(p.research, _value); emit UpdateResearch(_addr, p.research); } /** * @dev add virus for player * @param _addr player address * @param _value number of virus */ function addVirus(address _addr, uint256 _value) public onlyContractsMiniGame { Player storage p = players[_addr]; uint256 additionalVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD); p.virusNumber = SafeMath.add(p.virusNumber, additionalVirus); emit ChangeVirus(_addr, _value, 1); } /** * @dev subtract virus of player * @param _addr player address * @param _value number virus subtract */ function subVirus(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; uint256 subtractVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD); if ( p.virusNumber < subtractVirus ) { revert(); } p.virusNumber = SafeMath.sub(p.virusNumber, subtractVirus); emit ChangeVirus(_addr, _value, 2); } /** * @dev claim price pool to next new game * @param _addr mini game contract address * @param _value eth claim; */ function claimPrizePool(address _addr, uint256 _value) public onlyContractsMiniGame { require(prizePool > _value); prizePool = SafeMath.sub(prizePool, _value); MiniGameInterface MiniGame = MiniGameInterface( _addr ); MiniGame.fallback.value(_value)(); } //-------------------------------------------------------------------------- // PLAYERS //-------------------------------------------------------------------------- /** */ function buyEngineer(uint256[8] engineerNumbers) public payable disableContract { updateVirus(msg.sender); Player storage p = players[msg.sender]; uint256 priceCrystals = 0; uint256 priceEth = 0; uint256 research = 0; for (uint256 engineerIdx = 0; engineerIdx < numberOfEngineer; engineerIdx++) { uint256 engineerNumber = engineerNumbers[engineerIdx]; EngineerData memory e = engineers[engineerIdx]; // require for engineerNumber if(engineerNumber > e.limit || engineerNumber < 0) revert(); // engineer you want buy if (engineerNumber > 0) { uint256 currentEngineerCount = p.engineersCount[engineerIdx]; // update player data p.engineersCount[engineerIdx] = SafeMath.min(e.limit, SafeMath.add(p.engineersCount[engineerIdx], engineerNumber)); // calculate no research you want buy research = SafeMath.add(research, SafeMath.mul(SafeMath.sub(p.engineersCount[engineerIdx],currentEngineerCount), e.baseResearch)); // calculate price crystals and eth you will pay priceCrystals = SafeMath.add(priceCrystals, SafeMath.mul(e.basePrice, engineerNumber)); priceEth = SafeMath.add(priceEth, SafeMath.mul(e.baseETH, engineerNumber)); } } // check price eth if (priceEth < msg.value) revert(); uint256 devFeePrize = devFee(priceEth); distributedToOwner(devFeePrize); addMiningWarPrizePool(devFeePrize); addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3))); // pay and update MiningWar.subCrystal(msg.sender, priceCrystals); updateResearch(msg.sender, research); emit BuyEngineer(msg.sender, engineerNumbers, priceCrystals, priceEth, research); } /** * @dev update virus for player * @param _addr player address */ function updateVirus(address _addr) private { Player storage p = players[_addr]; p.virusNumber = calCurrentVirus(_addr); p.lastUpdateTime = now; } function calCurrentVirus(address _addr) public view returns(uint256 _currentVirus) { Player memory p = players[_addr]; uint256 secondsPassed = SafeMath.sub(now, p.lastUpdateTime); uint256 researchPerDay = getResearchPerDay(_addr); _currentVirus = p.virusNumber; if (researchPerDay > 0) { _currentVirus = SafeMath.add(_currentVirus, SafeMath.mul(researchPerDay, secondsPassed)); } } /** * @dev update research for player * @param _addr player address * @param _research number research want to add */ function updateResearch(address _addr, uint256 _research) private { Player storage p = players[_addr]; p.research = SafeMath.add(p.research, _research); emit UpdateResearch(_addr, p.research); } function getResearchPerDay(address _addr) public view returns( uint256 _researchPerDay) { Player memory p = players[_addr]; _researchPerDay = p.research; uint256 boosterIdx = hasBooster(_addr); if (boosterIdx != 999) { BoostData memory b = boostData[boosterIdx]; _researchPerDay = SafeMath.div(SafeMath.mul(_researchPerDay, b.boostRate), 100); } } /** * @dev get player data * @param _addr player address */ function getPlayerData(address _addr) public view returns( uint256 _virusNumber, uint256 _currentVirus, uint256 _research, uint256 _researchPerDay, uint256 _lastUpdateTime, uint256[8] _engineersCount ) { Player storage p = players[_addr]; for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) { _engineersCount[idx] = p.engineersCount[idx]; } _currentVirus= SafeMath.div(calCurrentVirus(_addr), VIRUS_MINING_PERIOD); _virusNumber = SafeMath.div(p.virusNumber, VIRUS_MINING_PERIOD); _lastUpdateTime = p.lastUpdateTime; _research = p.research; _researchPerDay = getResearchPerDay(_addr); } //-------------------------------------------------------------------------- // INTERNAL //-------------------------------------------------------------------------- function addPrizePool(uint256 _value) private { prizePool = SafeMath.add(prizePool, _value); } /** * @dev add 5% value of transaction payable */ function addMiningWarPrizePool(uint256 _value) private { MiningWar.fallback.value(_value)(); } /** * @dev calculate current crystals of player * @param _addr player address */ function calCurrentCrystals(address _addr) public view returns(uint256 _currentCrystals) { _currentCrystals = SafeMath.div(MiningWar.calCurrentCrystals(_addr), CRTSTAL_MINING_PERIOD); } function devFee(uint256 _amount) private pure returns(uint256) { return SafeMath.div(SafeMath.mul(_amount, 5), 100); } /** * @dev with transaction payable send 5% value for admin and sponsor * @param _value fee */ function distributedToOwner(uint256 _value) private { gameSponsor.transfer(_value); administrator.transfer(_value); } }
MainContract used this function to verify game's contract/
function isContractMiniGame() public pure returns(bool _isContractMiniGame) { _isContractMiniGame = true; }
13,067,412
./full_match/80001/0xf2F9Dc580289FC127D88f6A6FeF19b0e3c99BBCd/sources/contracts/ClearingHouse.sol
only cancel open orders if there are not enough free collateral with mmRatio or account is able to being liquidated.
function _cancelExcessOrders( address maker, address baseToken, bytes32[] memory orderIds ) internal { if (orderIds.length == 0) { return; } (_getFreeCollateralByRatio(maker, IClearingHouseConfig(_clearingHouseConfig).getMmRatio()) < 0) || _isLiquidatable(maker), "CH_NEXO" ); IOrderBook.RemoveLiquidityResponse memory removeLiquidityResponse; uint256 length = orderIds.length; for (uint256 i = 0; i < length; i++) { OpenOrder.Info memory order = IOrderBook(_orderBook).getOpenOrderById(orderIds[i]); IOrderBook.RemoveLiquidityResponse memory response = IOrderBook(_orderBook).removeLiquidity( IOrderBook.RemoveLiquidityParams({ maker: maker, baseToken: baseToken, lowerTick: order.lowerTick, upperTick: order.upperTick, liquidity: order.liquidity }) ); removeLiquidityResponse.base = removeLiquidityResponse.base.add(response.base); removeLiquidityResponse.quote = removeLiquidityResponse.quote.add(response.quote); removeLiquidityResponse.fee = removeLiquidityResponse.fee.add(response.fee); removeLiquidityResponse.takerBase = removeLiquidityResponse.takerBase.add(response.takerBase); removeLiquidityResponse.takerQuote = removeLiquidityResponse.takerQuote.add(response.takerQuote); emit LiquidityChanged( maker, baseToken, _quoteToken, order.lowerTick, order.upperTick, response.base.neg256(), response.quote.neg256(), order.liquidity.neg128(), response.fee ); } int256 realizedPnl = _settleBalanceAndRealizePnl(maker, baseToken, removeLiquidityResponse); uint256 sqrtPrice = _getSqrtMarkTwapX96(baseToken, 0); int256 openNotional = _getTakerOpenNotional(maker, baseToken); _emitPositionChanged( maker, baseToken, 0, openNotional, sqrtPrice ); }
9,454,016
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413 //Contract name: EthernautsExplore //Balance: 0.251 Ether //Verification Date: 4/24/2018 //Transacion Count: 727 // CODE STARTS HERE pragma solidity ^0.4.19; /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Ethernauts contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; function implementsERC721() public pure returns (bool); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // Extend this library for child contracts library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } } /// @dev Base contract for all Ethernauts contracts holding global constants and functions. contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); } /// @notice This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern. contract EthernautsAccessControl is EthernautsBase { // This facet controls access control for Ethernauts. // All roles have same responsibilities and rights, but there is slight differences between them: // // - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract. // It is initially set to the address that created the smart contract. // // - The CTO: The CTO can change contract address, oracle address and plan for upgrades. // // - The COO: The COO can change contract address and add create assets. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan /// @param newContract address pointing to new contract event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyCTO() { require(msg.sender == ctoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || msg.sender == cooAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO. /// @param _newCTO The address of the new CTO function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as oracle. /// @param _newOracle The address of oracle function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CTO account is compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Storage contract for Ethernauts Data. Common structs and constants. /// @notice This is our main data storage, constants and data types, plus // internal functions for managing the assets. It is isolated and only interface with // a list of granted contracts defined by CTO /// @author Ethernauts - Fernando Pauer contract EthernautsStorage is EthernautsAccessControl { function EthernautsStorage() public { // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is the initial CTO as well ctoAddress = msg.sender; // the creator of the contract is the initial CTO as well cooAddress = msg.sender; // the creator of the contract is the initial Oracle as well oracleAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents. function() external payable { require(msg.sender == address(this)); } /*** Mapping for Contracts with granted permission ***/ mapping (address => bool) public contractsGrantedAccess; /// @dev grant access for a contract to interact with this contract. /// @param _v2Address The contract address to grant access function grantAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan contractsGrantedAccess[_v2Address] = true; } /// @dev remove access from a contract to interact with this contract. /// @param _v2Address The contract address to be removed function removeAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan delete contractsGrantedAccess[_v2Address]; } /// @dev Only allow permitted contracts to interact with this contract modifier onlyGrantedContracts() { require(contractsGrantedAccess[msg.sender] == true); _; } modifier validAsset(uint256 _tokenId) { require(assets[_tokenId].ID > 0); _; } /*** DATA TYPES ***/ /// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy /// of this structure. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Asset { // Asset ID is a identifier for look and feel in frontend uint16 ID; // Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers uint8 category; // The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring uint8 state; // Attributes // byte pos - Definition // 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. // 00000010 - Producible - Product of a factory and/or factory contract. // 00000100 - Explorable- Product of exploration. // 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. // 00010000 - Permanent - Cannot be removed, always owned by a user. // 00100000 - Consumable - Destroyed after N exploration expeditions. // 01000000 - Tradable - Buyable and sellable on the market. // 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 attributes; // The timestamp from the block when this asset was created. uint64 createdAt; // The minimum timestamp after which this asset can engage in exploring activities again. uint64 cooldownEndBlock; // The Asset's stats can be upgraded or changed based on exploration conditions. // It will be defined per child contract, but all stats have a range from 0 to 255 // Examples // 0 = Ship Level // 1 = Ship Attack uint8[STATS_SIZE] stats; // Set to the cooldown time that represents exploration duration for this asset. // Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part. uint256 cooldown; // a reference to a super asset that manufactured the asset uint256 builtBy; } /*** CONSTANTS ***/ // @dev Sanity check that allows us to ensure that we are pointing to the // right storage contract in our EthernautsLogic(address _CStorageAddress) call. bool public isEthernautsStorage = true; /*** STORAGE ***/ /// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId /// of each asset is actually an index into this array. Asset[] public assets; /// @dev A mapping from Asset UniqueIDs to the price of the token. /// stored outside Asset Struct to save gas, because price can change frequently mapping (uint256 => uint256) internal assetIndexToPrice; /// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address. mapping (uint256 => address) internal assetIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) internal ownershipTokenCount; /// @dev A mapping from AssetUniqueIDs to an address that has been approved to call /// transferFrom(). Each Asset can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) internal assetIndexToApproved; /*** SETTERS ***/ /// @dev set new asset price /// @param _tokenId asset UniqueId /// @param _price asset price function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts { assetIndexToPrice[_tokenId] = _price; } /// @dev Mark transfer as approved /// @param _tokenId asset UniqueId /// @param _approved address approved function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts { assetIndexToApproved[_tokenId] = _approved; } /// @dev Assigns ownership of a specific Asset to an address. /// @param _from current owner address /// @param _to new owner address /// @param _tokenId asset UniqueId function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts { // Since the number of assets is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership assetIndexToOwner[_tokenId] = _to; // When creating new assets _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete assetIndexToApproved[_tokenId]; } } /// @dev A public method that creates a new asset and stores it. This /// method does basic checking and should only be called from other contract when the /// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts. /// @param _creatorTokenID The asset who is father of this asset /// @param _owner First owner of this asset /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) public onlyGrantedContracts returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); Asset memory asset = Asset({ ID: _ID, category: _category, builtBy: _creatorTokenID, attributes: bytes2(_attributes), stats: _stats, state: _state, createdAt: uint64(now), cooldownEndBlock: _cooldownEndBlock, cooldown: _cooldown }); uint256 newAssetUniqueId = assets.push(asset) - 1; // Check it reached 4 billion assets but let's just be 100% sure. require(newAssetUniqueId == uint256(uint32(newAssetUniqueId))); // store price assetIndexToPrice[newAssetUniqueId] = _price; // This will assign ownership transfer(address(0), _owner, newAssetUniqueId); return newAssetUniqueId; } /// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This /// This method doesn't do any checking and should only be called when the /// input data is known to be valid. /// @param _tokenId The token ID /// @param _creatorTokenID The asset that create that token /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown asset cooldown index function editAsset( uint256 _tokenId, uint256 _creatorTokenID, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint16 _cooldown ) external validAsset(_tokenId) onlyCLevel returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); // store price assetIndexToPrice[_tokenId] = _price; Asset storage asset = assets[_tokenId]; asset.ID = _ID; asset.category = _category; asset.builtBy = _creatorTokenID; asset.attributes = bytes2(_attributes); asset.stats = _stats; asset.state = _state; asset.cooldown = _cooldown; } /// @dev Update only stats /// @param _tokenId asset UniqueId /// @param _stats asset state, see Asset Struct description function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].stats = _stats; } /// @dev Update only asset state /// @param _tokenId asset UniqueId /// @param _state asset state, see Asset Struct description function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].state = _state; } /// @dev Update Cooldown for a single asset /// @param _tokenId asset UniqueId /// @param _cooldown asset state, see Asset Struct description function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].cooldown = _cooldown; assets[_tokenId].cooldownEndBlock = _cooldownEndBlock; } /*** GETTERS ***/ /// @notice Returns only stats data about a specific asset. /// @dev it is necessary due solidity compiler limitations /// when we have large qty of parameters it throws StackTooDeepException /// @param _tokenId The UniqueId of the asset of interest. function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) { return assets[_tokenId].stats; } /// @dev return current price of an asset /// @param _tokenId asset UniqueId function priceOf(uint256 _tokenId) public view returns (uint256 price) { return assetIndexToPrice[_tokenId]; } /// @notice Check if asset has all attributes passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes == _attributes; } /// @notice Check if asset has any attribute passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes != 0x0; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _category see AssetCategory in EthernautsBase for possible states function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _state see enum AssetState in EthernautsBase for possible states function isState(uint256 _tokenId, uint8 _state) public view returns (bool) { return assets[_tokenId].state == _state; } /// @notice Returns owner of a given Asset(Token). /// @dev Required for ERC-721 compliance. /// @param _tokenId asset UniqueId function ownerOf(uint256 _tokenId) public view returns (address owner) { return assetIndexToOwner[_tokenId]; } /// @dev Required for ERC-721 compliance /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _tokenId asset UniqueId function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) { return assetIndexToApproved[_tokenId]; } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return assets.length; } /// @notice List all existing tokens. It can be filtered by attributes or assets with owner /// @param _owner filter all assets by owner function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns( uint256[6][] ) { uint256 totalAssets = assets.length; if (totalAssets == 0) { // Return an empty array return new uint256[6][](0); } else { uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets); uint256 resultIndex = 0; bytes2 hasAttributes = bytes2(_withAttributes); Asset memory asset; for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) { asset = assets[tokenId]; if ( (asset.state != uint8(AssetState.Used)) && (assetIndexToOwner[tokenId] == _owner || _owner == address(0)) && (asset.attributes & hasAttributes == hasAttributes) ) { result[resultIndex][0] = tokenId; result[resultIndex][1] = asset.ID; result[resultIndex][2] = asset.category; result[resultIndex][3] = uint256(asset.attributes); result[resultIndex][4] = asset.cooldown; result[resultIndex][5] = assetIndexToPrice[tokenId]; resultIndex++; } } return result; } } } /// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant. /// @notice This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // It interfaces with EthernautsStorage provinding basic functions as create and list, also holds // reference to logic contracts as Auction, Explore and so on /// @author Ethernatus - Fernando Pauer /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 contract EthernautsOwnership is EthernautsAccessControl, ERC721 { /// @dev Contract holding only data. EthernautsStorage public ethernautsStorage; /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "Ethernauts"; string public constant symbol = "ETNT"; /********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/ /**********************************************************************/ bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); /*** EVENTS ***/ // Events as per ERC-721 event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed approved, uint256 tokens); /// @dev When a new asset is create it emits build event /// @param owner The address of asset owner /// @param tokenId Asset UniqueID /// @param assetId ID that defines asset look and feel /// @param price asset price event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price); function implementsERC721() public pure returns (bool) { return true; } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721. /// @param _interfaceID interface signature ID function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Checks if a given address is the current owner of a particular Asset. /// @param _claimant the address we are validating against. /// @param _tokenId asset UniqueId, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.ownerOf(_tokenId) == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _claimant the address we are confirming asset is approved for. /// @param _tokenId asset UniqueId, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.approvedFor(_tokenId) == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Assets on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ethernautsStorage.approve(_tokenId, _approved); } /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ethernautsStorage.balanceOf(_owner); } /// @dev Required for ERC-721 compliance. /// @notice Transfers a Asset to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Ethernauts specifically) or your Asset may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Asset to transfer. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets // (except very briefly after it is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the storage contract to prevent accidental // misuse. Auction or Upgrade contracts should only take ownership of assets // through the allow + transferFrom flow. require(_to != address(ethernautsStorage)); // You can only send your own asset. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. ethernautsStorage.transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Grant another address the right to transfer a specific Asset via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Asset that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transferred. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function _transferFrom( address _from, address _to, uint256 _tokenId ) internal { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets (except for used assets). require(_owns(_from, _tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). ethernautsStorage.transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transfered. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { _transferFrom(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address _from = ethernautsStorage.ownerOf(_tokenId); // Safety check to prevent against an unexpected 0x0 default. require(_from != address(0)); _transferFrom(_from, msg.sender, _tokenId); } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return ethernautsStorage.totalSupply(); } /// @notice Returns owner of a given Asset(Token). /// @param _tokenId Token ID to get owner. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ethernautsStorage.ownerOf(_tokenId); require(owner != address(0)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createNewAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats ) external onlyCLevel returns (uint256) { // owner must be sender require(_owner != address(0)); uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, 0, 0 ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice verify if token is in exploration time /// @param _tokenId The Token ID that can be upgraded function isExploring(uint256 _tokenId) public view returns (bool) { uint256 cooldown; uint64 cooldownEndBlock; (,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId); return (cooldown > now) || (cooldownEndBlock > uint64(block.number)); } } /// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts /// @author Ethernatus - Fernando Pauer contract EthernautsLogic is EthernautsOwnership { // Set in case the logic contract is broken and an upgrade is required address public newContractAddress; /// @dev Constructor function EthernautsLogic() public { // the creator of the contract is the initial CEO, COO, CTO ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; // Starts paused. paused = true; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCTO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @dev set a new reference to the NFT ownership contract /// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage. function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(ethernautsStorage != address(0)); require(newContractAddress == address(0)); // require this contract to have access to storage contract require(ethernautsStorage.contractsGrantedAccess(address(this)) == true); // Actually unpause the contract. super.unpause(); } // @dev Allows the COO to capture the balance available to the contract. function withdrawBalances(address _to) public onlyCLevel { _to.transfer(this.balance); } /// return current contract balance function getBalance() public view onlyCLevel returns (uint256) { return this.balance; } } /// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space. /// @notice An owned ship can be send on an expedition. Exploration takes time // and will always result in “success”. This means the ship can never be destroyed // and always returns with a collection of loot. The degree of success is dependent // on different factors as sector stats, gamma ray burst number and ship stats. // While the ship is exploring it cannot be acted on in any way until the expedition completes. // After the ship returns from an expedition the user is then rewarded with a number of objects (assets). /// @author Ethernatus - Fernando Pauer contract EthernautsExplore is EthernautsLogic { /// @dev Delegate constructor to Nonfungible contract. function EthernautsExplore() public EthernautsLogic() {} /*** EVENTS ***/ /// emit signal to anyone listening in the universe event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time); event Result(uint256 shipId, uint256 sectorID); /*** CONSTANTS ***/ uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255 // @dev Sanity check that allows us to ensure that we are pointing to the // right explore contract in our EthernautsCrewMember(address _CExploreAddress) call. bool public isEthernautsExplore = true; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; uint256 public TICK_TIME = 15; // time is always in minutes // exploration fee uint256 public percentageCut = 90; int256 public SPEED_STAT_MAX = 30; int256 public RANGE_STAT_MAX = 20; int256 public MIN_TIME_EXPLORE = 60; int256 public MAX_TIME_EXPLORE = 2160; int256 public RANGE_SCALE = 2; /// @dev Sector stats enum SectorStats {Size, Threat, Difficulty, Slots} /// @dev hold all ships in exploration uint256[] explorers; /// @dev A mapping from Ship token to the exploration index. mapping (uint256 => uint256) public tokenIndexToExplore; /// @dev A mapping from Asset UniqueIDs to the sector token id. mapping (uint256 => uint256) public tokenIndexToSector; /// @dev A mapping from exploration index to the crew token id. mapping (uint256 => uint256) public exploreIndexToCrew; /// @dev A mission counter for crew. mapping (uint256 => uint16) public missions; /// @dev A mapping from Owner Cut (wei) to the sector token id. mapping (uint256 => uint256) public sectorToOwnerCut; mapping (uint256 => uint256) public sectorToOracleFee; /// @dev Get a list of ship exploring our universe function getExplorerList() public view returns( uint256[3][] ) { uint256[3][] memory tokens = new uint256[3][](50); uint256 index = 0; for(uint256 i = 0; i < explorers.length && index < 50; i++) { if (explorers[i] > 0) { tokens[index][0] = explorers[i]; tokens[index][1] = tokenIndexToSector[explorers[i]]; tokens[index][2] = exploreIndexToCrew[i]; index++; } } if (index == 0) { // Return an empty array return new uint256[3][](0); } else { return tokens; } } /// @dev Get a list of ship exploring our universe /// @param _shipTokenId The Token ID that represents a ship function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) { for(uint256 i = 0; i < explorers.length; i++) { if (explorers[i] == _shipTokenId) { return i; } } return 0; } function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel { sectorToOwnerCut[_sectorId] = _ownerCut; } function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel { sectorToOracleFee[_sectorId] = _oracleFee; } function setTickTime(uint256 _tickTime) external onlyCLevel { TICK_TIME = _tickTime; } function setPercentageCut(uint256 _percentageCut) external onlyCLevel { percentageCut = _percentageCut; } function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel { missions[_tokenId] = _total; } /// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players /// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate. /// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%. /// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object. /// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once /// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration. /// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats. /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused { // charge a fee for each exploration when the results are ready require(msg.value >= sectorToOwnerCut[_sectorTokenId]); // check if Asset is a ship or not require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship))); // check if _sectorTokenId is a sector or not require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector))); // Ensure the Ship is in available state, otherwise it cannot explore require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available))); // ship could not be in exploration require(tokenIndexToExplore[_shipTokenId] == 0); require(!isExploring(_shipTokenId)); // check if explorer is ship owner require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId)); // check if owner sector is not empty address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId); // check if there is a crew and validating crew member if (_crewTokenId > 0) { // crew member should not be in exploration require(!isExploring(_crewTokenId)); // check if Asset is a crew or not require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember))); // check if crew member is same owner require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId)); } /// store exploration data tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1; tokenIndexToSector[_shipTokenId] = _sectorTokenId; uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId); uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId); // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId; missions[_crewTokenId]++; //// grab crew stats and merge with ship uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId); _shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)]; _shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)]; if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT; } if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT; } } /// set exploration time uint256 time = uint256(_explorationTime( _shipStats[uint256(ShipStats.Range)], _shipStats[uint256(ShipStats.Speed)], _sectorStats[uint256(SectorStats.Size)] )); // exploration time in minutes converted to seconds time *= 60; uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number); ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock); // check if there is a crew store data and set crew exploration time if (_crewTokenId > 0) { /// store crew exploration time ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock); } // to avoid mistakes and charge unnecessary extra fees uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]); uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId]; /// emit signal to anyone listening in the universe Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time); // keeping oracle accounts with balance oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]); // paying sector owner sectorOwner.transfer(payment); // send excess back to explorer msg.sender.transfer(feeExcess); } /// @notice Exploration is complete and at most 10 Objects will return during one exploration. /// @param _shipTokenId The Token ID that represents a ship and can explore /// @param _sectorTokenId The Token ID that represents a sector and can be explored /// @param _IDs that represents a object returned from exploration /// @param _attributes that represents attributes for each object returned from exploration /// @param _stats that represents all stats for each object returned from exploration function explorationResults( uint256 _shipTokenId, uint256 _sectorTokenId, uint16[10] _IDs, uint8[10] _attributes, uint8[STATS_SIZE][10] _stats ) external onlyOracle { uint256 cooldown; uint64 cooldownEndBlock; uint256 builtBy; (,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId); address owner = ethernautsStorage.ownerOf(_shipTokenId); require(owner != address(0)); /// create objects returned from exploration uint256 i = 0; for (i = 0; i < 10 && _IDs[i] > 0; i++) { _buildAsset( _sectorTokenId, owner, 0, _IDs[i], uint8(AssetCategory.Object), uint8(_attributes[i]), _stats[i], cooldown, cooldownEndBlock ); } // to guarantee at least 1 result per exploration require(i > 0); /// remove from explore list explorers[tokenIndexToExplore[_shipTokenId]] = 0; delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; /// emit signal to anyone listening in the universe Result(_shipTokenId, _sectorTokenId); } /// @notice Cancel ship exploration in case it get stuck /// @param _shipTokenId The Token ID that represents a ship and can explore function cancelExplorationByShip( uint256 _shipTokenId ) external onlyCLevel { uint256 index = tokenIndexToExplore[_shipTokenId]; if (index > 0) { /// remove from explore list explorers[index] = 0; if (exploreIndexToCrew[index] > 0) { delete exploreIndexToCrew[index]; } } delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; } /// @notice Cancel exploration in case it get stuck /// @param _index The exploration position that represents a exploring ship function cancelExplorationByIndex( uint256 _index ) external onlyCLevel { uint256 shipId = explorers[_index]; /// remove from exploration list explorers[_index] = 0; if (shipId > 0) { delete tokenIndexToExplore[shipId]; delete tokenIndexToSector[shipId]; } if (exploreIndexToCrew[_index] > 0) { delete exploreIndexToCrew[_index]; } } /// @notice Add exploration in case contract needs to be add trxs from previous contract /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function addExplorationByShip( uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId ) external onlyCLevel whenPaused { uint256 index = explorers.push(_shipTokenId) - 1; /// store exploration data tokenIndexToExplore[_shipTokenId] = index; tokenIndexToSector[_shipTokenId] = _sectorTokenId; // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[index] = _crewTokenId; missions[_crewTokenId]++; } ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown see Asset Struct description /// @param _cooldownEndBlock see Asset Struct description function _buildAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) private returns (uint256) { uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, _cooldown, _cooldownEndBlock ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size /// along with the Ship’s Range and Speed. /// @param _shipRange ship range /// @param _shipSpeed ship speed /// @param _sectorSize sector size function _explorationTime( uint8 _shipRange, uint8 _shipSpeed, uint8 _sectorSize ) private view returns (int256) { int256 minToExplore = 0; minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1; minToExplore = -72 * minToExplore; minToExplore += MAX_TIME_EXPLORE; uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX)); uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE); int256 minExplore = (minToExplore - MIN_TIME_EXPLORE); minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange)); minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10); minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE); return minToExplore; } /// @notice calcs a perc without float or double :( function fraction(int256 _subject, int256 _numerator, int256 _denominator) private pure returns (int256) { int256 division = _subject * _numerator - _subject * _denominator; int256 total = _subject * _denominator + division; return total / _denominator; } /// @notice Any C-level can fix how many seconds per blocks are currently observed. /// @param _secs The seconds per block function setSecondsPerBlock(uint256 _secs) external onlyCLevel { require(_secs > 0); secondsPerBlock = _secs; } }
Assigns a new address to act as the COO. Only available to the current COO or CEO. _newCOO The address of the new COO
function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; }
1,044,127
./partial_match/1/0x43c6eE9D5B2369C5484f69E2Eb3361466855beDd/sources/FabricaToken.sol
See {IERC1155-isApprovedForAll}./
function isApprovedForAll(address account, address operator) public view virtual override whenNotPaused returns (bool) { return _operatorApprovals[account][operator]; }
2,672,115
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; /** * todo create struct or contract for a mapping of addresses to byte32, for user account passwords! * libraries with internal functions have to function body injected into all callsites (this increases size and gas cost) * however, internal libraries do not need to be deployed, only included with the contracts that use them */ //note: this causes an error if bytes is above 127, (beyond human readable ASCII range) //function concat(bytes1 lhs, string memory rhs)public pure returns(string memory){ //string memory s = string(abi.encode(lhs)); //return string(abi.encodePacked(s, rhs)); //} /// /// @title Bytes Logic Library /// @author Tyler R. Drury - 4/3/2021, All Rights Reserved /// @notice trivial functions for the bytes data type not provided natively by Solidity. /// library BytesLogic { //using LogicConstraints for bool; //bytes intneral constant EMPTY = bytes(""); bytes intneral constant NULL = 0x00; //bytes(""); bytes intneral constant FF = 0xFF; /** function lengthEqual( bytes memory lhs, bytes memory rhs )internal pure returns( bool ){ if(lhs.length == rhs.length){ return true; } return false; } function lengthEqualAndNonZero( bytes memory lhs, bytes memory rhs )internal pure returns( bool ){ if(lengthNonZero(lhs) && lengthNonZero(rhs) ){ return lhs.length == rhs.length, } return false; } function lengthEqual( bytes memory lhs, uint byteCount )internal pure returns( bool ){ if(lengthNonZero(lhs) && lengthNonZero(rhs) ){ return lhs.length == rhs.length, } return false; } /// /// @dev timing attack resistent equality operator (==) for arbitrary length bytes /// function equal( bytes lhs, bytes rhs )internal pure returns( bool ){ if(lengthNotEqual(lhs, rhs)){ return false; } return xor( keccak256(lhs), keccak256(rhs) ) == bytes32(NULL); } /// /// @dev timing attack resistent inequality operator (==) for arbitrary length bytes /// function notEqual( bytes memory lhs, bytes memory rhs )internal pure returns( bool ){ if(lengthNotEqual(lhs, rhs)){ return true; } return xor( keccak256(lhs), keccak256(rhs) ) != bytes32(NULL); } function lengthEqual( bytes memory b, uint byteCount )internal pure returns( bool ){ return lhs.length == byteCount; } function lengthNotEqual( bytes memory b, uint byteCount )internal pure returns( bool ){ return lhs.length != byteCount; } function lengthGreaterThan( bytes memory b, uint byteCount )internal pure returns( bool ){ return lhs.length > byteCount; } function lengthGreaterThanOrEqual( bytes memory b, uint byteCount )internal pure returns( bool ){ return lhs.length >= byteCount; } function lengthLessThan( bytes memory b, uint byteCount )internal pure returns( bool ){ return lhs.length < byteCount; } function lengthLessOrEqualThan( bytes memory b, uint byteCount )internal pure returns( bool ){ return lhs.length <= byteCount; } function lengthNonZero( bytes memory b )internal pure returns( bool ){ return lengthGreaterThan(lhs, 0); } */ /** function and( bytes lhs, bytes rhs )internal pure returns( bytes memory ){ //requireTrue(lhs.length > 0); //requireTrue(lhs.length == rhs.length); return lhs & rhs; } function or( bytes lhs, bytes rhs )internal pure returns( bytes memory ){ //requireTrue(lhs.length > 0); //requireTrue(lhs.length == rhs.length); return lhs | rhs; } function xor( bytes lhs, bytes rhs )internal pure returns( bytes memory ){ //requireTrue(lhs.length > 0); //requireTrue(lhs.length == rhs.length); return lhs ^ rhs; } function not( bytes lhs )internal pure returns( bytes memory ){ return ~lhs; } /** function lshift( bytes lhs, uint256 rhs )internal pure returns( bytes memory ){ return lhs << rhs; } function rshift( bytes lhs, uint256 rhs )internal pure returns( bytes memory ){ return lhs >> rhs; } */ //function char( //bytes memory lhs, //uint256 index //)internal pure returns( //bool //){ //uint256 L = lhs.length; //require(L > 0, 'bytes must have non-zero length'); //require(index < L, 'index out of bounds'); //require(L <= uint256(-1), 'bytes exceed maxmum allowable size'); //return lhs[index]; //} function null( bytes lhs )internal pure returns( bool ){ return lengthEqual(lhs, 1) && equal(lhs, NULL); } // //function notNull( //bytes lhs //)internal pure returns( //bool //){ //return lengthGreaterThan(lhs, 1) && notEqual(lhs, NULL); //} /* function empty( bytes lhs )internal pure returns( bool ){ return lhs == EMPTY; } function notEmpty( bytes lhs )internal pure returns( bool ){ return lhs != EMPTY; } */ /** function notEmptyAndNotEqual( bytes lhs, bytes rhs )public pure returns( bool ){ return notEmpty( lhs ) && notEmpty( rhs ) && notEqual(lhs,rhs); } function notEmptyAndAreEqual( bytes lhs, bytes rhs )public pure returns( bool ){ return notEmpty( lhs ) && notEmpty( rhs ) && equal(lhs,rhs); } */ }
requireTrue(lhs.length > 0);requireTrue(lhs.length == rhs.length);
function or( bytes lhs, bytes rhs )internal pure returns( bytes memory ){ return lhs | rhs; }
12,960,342
// Sources flattened with hardhat v2.1.2 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // File @openzeppelin/contracts/proxy/Clones.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // File contracts/governance/IMaintainersRegistry.sol pragma solidity 0.6.12; interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); } // File contracts/governance/ICongressMembersRegistry.sol pragma solidity 0.6.12; /** * ICongressMembersRegistry contract. * @author Nikola Madjarevic * Date created: 13.9.21. * Github: madjarevicn */ interface ICongressMembersRegistry { function isMember(address _address) external view returns (bool); function getMinimalQuorum() external view returns (uint256); } // File contracts/system/TokensFarmUpgradable.sol pragma solidity 0.6.12; //to be fixed contract TokensFarmUpgradable { // Address of tokens congress address public tokensFarmCongress; // Instance of maintainers registry object IMaintainersRegistry public maintainersRegistry; // Only maintainer modifier modifier onlyMaintainer { require( maintainersRegistry.isMaintainer(msg.sender), "TokensFarmUpgradable: Restricted only to Maintainer" ); _; } // Only tokens farm congress modifier modifier onlyTokensFarmCongress { require( msg.sender == tokensFarmCongress, "TokensFarmUpgradable: Restricted only to TokensFarmCongress" ); _; } /** * @notice function to set congress and maintainers registry address * * @param _tokensFarmCongress - address of tokens farm congress * @param _maintainersRegistry - address of maintainers registry */ function setCongressAndMaintainersRegistry( address _tokensFarmCongress, address _maintainersRegistry ) internal { require( _tokensFarmCongress != address(0x0), "tokensFarmCongress can not be 0x0 address" ); require( _maintainersRegistry != address(0x0), "_maintainersRegistry can not be 0x0 address" ); tokensFarmCongress = _tokensFarmCongress; maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } /** * @notice function to set new maintainers registry address * * @param _maintainersRegistry - address of new maintainers registry */ function setMaintainersRegistry( address _maintainersRegistry ) external onlyTokensFarmCongress { require( _maintainersRegistry != address(0x0), "_maintainersRegistry can not be 0x0 address" ); maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } /** * @notice function to set new congress registry address * * @param _tokensFarmCongress - address of new tokens farm congress */ function setTokensFarmCongress( address _tokensFarmCongress ) external onlyTokensFarmCongress { require( _tokensFarmCongress != address(0x0), "_maintainersRegistry can not be 0x0 address" ); tokensFarmCongress = _tokensFarmCongress; } } // File contracts/interfaces/ITokensFarm.sol pragma solidity 0.6.12; interface ITokensFarm { function fund(uint256 _amount) external; function setMinTimeToStake(uint256 _minTimeToStake) external; function setIsEarlyWithdrawAllowed(bool _isEarlyWithdrawAllowed) external; function setStakeFeePercent(uint256 _stakeFeePercent) external; function setRewardFeePercent(uint256 _rewardFeePercent) external; function setFlatFeeAmount(uint256 _flatFeeAmount) external; function setIsFlatFeeAllowed(bool _isFlatFeeAllowed) external; function withdrawCollectedFeesERC() external; function withdrawCollectedFeesETH() external; function withdrawTokensIfStuck(address _erc20, uint256 _amount, address _beneficiary) external; function initialize( address _erc20, uint256 _rewardPerSecond, uint256 _startTime, uint256 _minTimeToStake, bool _isEarlyWithdrawAllowed, uint256 _penalty, address _tokenStaked, uint256 _stakeFeePercent, uint256 _rewardFeePercent, uint256 _flatFeeAmount, address payable _feeCollector, bool _isFlatFeeAllowed, address _farmImplementation ) external; function setFeeCollector(address payable _feeCollector) external ; } // File contracts/TokensFarmFactory.sol pragma solidity 0.6.12; contract TokensFarmFactory is TokensFarmUpgradable, Initializable { using SafeMath for uint256; using SafeERC20 for IERC20; using Clones for *; // Array of Tokens Farm that are deployed address[] public deployedTokensFarms; // FeeCollector + CongressAddress address payable public feeCollector; // Address of deployed tokens farm contract address public farmImplementation; // Events event DeployedFarm(address indexed farmAddress); event TokensFarmImplementationSet(address indexed farmImplementation); event FeeCollectorSet(address indexed feeCollector); /** * @notice function sets initial state of contract * * @param _farmImplementation- address of deployed farm * @param _tokensFarmCongress - address of farm congress * @param _maintainersRegistry - address of maintainers registry * @param _feeCollector - address of feeCollector */ function initialize( address _farmImplementation, address _tokensFarmCongress, address _maintainersRegistry, address payable _feeCollector ) external initializer { require( _farmImplementation != address(0), "farmImplementation can not be 0x0 address" ); require( _feeCollector != address(0), "_feeCollector can not be 0x0 address" ); // set congress and maintainers registry address setCongressAndMaintainersRegistry( _tokensFarmCongress, _maintainersRegistry ); // address of fee collector feeCollector = _feeCollector; // address of tokens farm contract farmImplementation = _farmImplementation; } /** * @notice function funds the farm * * @param _farmAddress - function will operate on * farm with this address * @param _rewardToken - address of reward token * @param _amount - funding the farm with this amount of tokens */ function _fundInternal( address _farmAddress, address _rewardToken, uint256 _amount ) internal { require( _farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); // instance of erc20 contract IERC20 rewardToken = IERC20(_rewardToken); // approval of transaction rewardToken.approve(_farmAddress, _amount); ITokensFarm tokensFarm = ITokensFarm(_farmAddress); tokensFarm.fund(_amount); } /** * @notice function to check does factory has enough funds * * @param _rewardToken - address of reward token * @param _totalBudget - funding the farm * with this amount of tokens */ function _sufficientFunds( address _rewardToken, uint256 _totalBudget ) internal view returns(bool) { // instance of erc20 contract IERC20 rewardToken = IERC20(_rewardToken); return rewardToken.balanceOf(address(this)) >= _totalBudget; } /** * @notice function deploys and funds farms * * @dev store their addresses in array * @dev deploys tokens farm proxy contract * @dev initializing of contract * * @param _rewardToken - address of reward token * @param _rewardPerSecond - number of reward per second * @param _minTimeToStake - how much time needs to past before staking * @param _isEarlyWithdrawAllowed - is early withdraw allowed or not * @param _penalty - ENUM(what type of penalty) * @param _tokenStaked - address of token which is staked * @param _stakeFeePercent - fee percent for staking * @param _rewardFeePercent - fee percent for reward distribution * @param _flatFeeAmount - flat fee amount * @param _isFlatFeeAllowed - is flat fee allowed or not */ function deployAndFundTokensFarm( address _rewardToken, uint256 _rewardPerSecond, uint256 _minTimeToStake, bool _isEarlyWithdrawAllowed, uint256 _penalty, address _tokenStaked, uint256 _stakeFeePercent, uint256 _rewardFeePercent, uint256 _flatFeeAmount, bool _isFlatFeeAllowed, uint256 _totalBudget ) external onlyMaintainer { require( _sufficientFunds(_rewardToken, _totalBudget), "There is not enough tokens left in factory to fund" ); // Creates clone of TokensFarm smart contract address clone = Clones.clone(farmImplementation); // Deploy tokens farm; ITokensFarm(clone).initialize( _rewardToken, _rewardPerSecond, block.timestamp + 10, _minTimeToStake, _isEarlyWithdrawAllowed, _penalty, _tokenStaked, _stakeFeePercent, _rewardFeePercent, _flatFeeAmount, feeCollector, _isFlatFeeAllowed, farmImplementation ); // Add deployed farm to array of deployed farms deployedTokensFarms.push(clone); // Funding the farm _fundInternal(clone, _rewardToken, _totalBudget); // Emits event with farms address emit DeployedFarm(clone); } /** * @notice function funds again the farm if necessary * * @param farmAddress - function will operate * on farm with this address * param rewardToken - address of reward token * @param amount - funding the farm with this amount of tokens */ function fundTheSpecificFarm( address farmAddress, address rewardToken, uint256 amount ) external onlyMaintainer { _fundInternal(farmAddress, rewardToken, amount); } /** * @notice function withdraws collected fees in ERC value * * @param farmAddress - function will operate on * farm with this address */ function withdrawCollectedFeesERCOnSpecificFarm( address farmAddress ) external onlyTokensFarmCongress { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.withdrawCollectedFeesERC(); } /** * @notice function withdraws collected fees in ETH value * * @param farmAddress - function will operate on * farm with this address */ function withdrawCollectedFeesETHOnSpecificFarm( address farmAddress ) external onlyTokensFarmCongress { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.withdrawCollectedFeesETH(); } /** * @notice function withdraws stuck tokens on farm * * @param farmAddress - function will operate on * farm with this address * @param _erc20 - address of token that is stuck * @param _amount - how many was deposited * @param _beneficiary - address of user * that deposited by mistake */ function withdrawTokensIfStuckOnSpecificFarm( address farmAddress, address _erc20, uint256 _amount, address _beneficiary ) external onlyTokensFarmCongress { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.withdrawTokensIfStuck(_erc20, _amount, _beneficiary); } /** * @notice function is setting address of deployed * tokens farm contract * * @param _farmImplementation - address of new tokens farm contract */ function setTokensFarmImplementation( address _farmImplementation ) external onlyTokensFarmCongress { require( _farmImplementation != address(0), "farmImplementation can not be 0x0 address" ); farmImplementation = _farmImplementation; emit TokensFarmImplementationSet(farmImplementation); } /** * @notice function is setting new address of fee collector * * @param _feeCollector - address of new fee collector */ function setFeeCollector( address payable _feeCollector ) external onlyTokensFarmCongress { require( _feeCollector != address(0), "Fee Collector can not be 0x0 address" ); feeCollector = _feeCollector; emit FeeCollectorSet(feeCollector); } /** * @notice function is setting new address of fee collector * on active farm * * @param farmAddress - address of farm */ function setCurrentFeeCollectorOnSpecificFarm( address farmAddress ) external onlyTokensFarmCongress { require( farmAddress != address(0x0), "Farm address can not be 0x0 address" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setFeeCollector(feeCollector); } /** * @notice function is setting variable minTimeToStake in tokens farm * * @param farmAddress - function will operate on farm with this address * @param _minTimeToStake - value of variable that needs to be set */ function setMinTimeToStakeOnSpecificFarm( address farmAddress, uint256 _minTimeToStake ) external onlyMaintainer { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); require(_minTimeToStake >= 0, "Minimal time can't be under 0"); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setMinTimeToStake(_minTimeToStake); } /** * @notice function is setting state if isEarlyWithdrawAllowed in tokens farm * * @param farmAddress - function will operate on farm with this address * @param _isEarlyWithdrawAllowed - state of variable that needs to be set */ function setIsEarlyWithdrawAllowedOnSpecificFarm( address farmAddress, bool _isEarlyWithdrawAllowed ) external onlyMaintainer { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setIsEarlyWithdrawAllowed(_isEarlyWithdrawAllowed); } /** * @notice function is setting variable stakeFeePercent in tokens farm * * @param farmAddress - function will operate on farm with this address * @param _stakeFeePercent - value of variable that needs to be set */ function setStakeFeePercentOnSpecificFarm( address farmAddress, uint256 _stakeFeePercent ) external onlyMaintainer { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); require( _stakeFeePercent > 0 && _stakeFeePercent < 100, "Stake fee percent must be between 0 and 100" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setStakeFeePercent(_stakeFeePercent); } /** * @notice function is setting variable rewardFeePercent in tokens farm * * @param farmAddress - function will operate on farm with this address * @param _rewardFeePercent - value of variable that needs to be set */ function setRewardFeePercentOnSpecificFarm( address farmAddress, uint256 _rewardFeePercent ) external onlyMaintainer { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); require( _rewardFeePercent > 0 && _rewardFeePercent < 100, "Reward fee percent must be between 0 and 100" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setRewardFeePercent(_rewardFeePercent); } /** * @notice function is setting variable flatFeeAmount in tokens farm * * @param farmAddress - function will operate on farm with this address * @param _flatFeeAmount - value of variable that needs to be set */ function setFlatFeeAmountOnSpecificFarm( address farmAddress, uint256 _flatFeeAmount ) external onlyMaintainer { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); require(_flatFeeAmount >= 0, "Flat fee can't be under 0"); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setFlatFeeAmount(_flatFeeAmount); } /** * @notice function is setting variable isFlatFeeAllowed in tokens farm * * @param farmAddress - function will operate on farm with this address * @param _isFlatFeeAllowed - state of variable that needs to be set */ function setIsFlatFeeAllowedOnSpecificFarm( address farmAddress, bool _isFlatFeeAllowed ) external onlyMaintainer { require( farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); ITokensFarm tokensFarm = ITokensFarm(farmAddress); tokensFarm.setIsFlatFeeAllowed(_isFlatFeeAllowed); } /** * @notice function returns address of last deployed farm * * @dev can be used on BE as additional checksum next to event emitted in tx * * @return address of last deployed farm */ function getLastDeployedFarm() external view returns (address) { if (deployedTokensFarms.length == 0) { // Means no farms deployed yet. return address(0); } // Deployed last deployed farm. return deployedTokensFarms[deployedTokensFarms.length - 1]; } /** * @notice function returns array, * of deployed farms(from start to end) * * @param start - beginning index of array * @param end - ending index of array * * @return array made of address of deployed tokens farm */ function getDeployedTokensFarm( uint256 start, uint256 end ) external view returns (address[] memory) { require(start < end, "Start should be less than end"); require( start >= 0 && end <= deployedTokensFarms.length, "One of the index is out of range" ); address[] memory tokensFarms = new address[](end - start); uint256 counter; for (uint256 i = start; i < end; i++) { tokensFarms[counter] = deployedTokensFarms[i]; counter++; } return tokensFarms; } }
function funds the farm _farmAddress - function will operate on farm with this address _rewardToken - address of reward token _amount - funding the farm with this amount of tokens/ instance of erc20 contract approval of transaction
function _fundInternal( address _farmAddress, address _rewardToken, uint256 _amount ) internal { require( _farmAddress != address(0x0), "Farm's address can't be 0x0 address" ); IERC20 rewardToken = IERC20(_rewardToken); rewardToken.approve(_farmAddress, _amount); ITokensFarm tokensFarm = ITokensFarm(_farmAddress); tokensFarm.fund(_amount); }
11,958,851
./full_match/80001/0x93606Db8e1340eBa115633Cc8a031D379D7638C6/sources/contracts/dev/vendor/openzeppelin-solidity/v.4.8.0/contracts/utils/SafeCast.sol
Returns the downcasted int80 from int256, reverting on overflow (when the input is less than smallest int80 or greater than largest int80). Counterpart to Solidity's `int80` operator. Requirements: - input must fit into 80 bits _Available since v4.7._/
function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); }
5,640,092
./full_match/1/0x46d9F045F60B1613bd4eC0D0eE2b3B47Cb6501d9/sources/src/TokenFactory.sol
checks if an upgrade is valid
function isValidUpgrade( address prevImpl, address newImpl ) external view returns (bool) { return upgrades[prevImpl][newImpl]; }
4,974,650
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /* __________________________________ | | | $ + $ + $ + $ + $ + $ + $ + $ + $| |+ $ + $ + $ + $ + $ + $ + $ + $ + | | + $ + $ + $ + $ + $ + $ + $ + $ +| |$ + $ + $ + $ + $ + $ + $ + $ + $ | | $ + $ + $ + $ + $ + $ + $ + $ + $| |+ $ + $ + $ + $ + $ + $ + $ + $ + | | + $ + $ + $ + $ + $ + $ + $ + $ +| |__________________________________| */ /** * @title NFT Broker * @author CXIP-Labs * @notice A simple smart contract for selling NFTs from a private storefront. * @dev The entire logic and functionality of the smart contract is self-contained. */ contract NFTBroker { /** * @dev Address of admin user. Primarily used as an additional recovery address. */ address private _admin; /** * @dev Address of contract owner. This address can run all onlyOwner functions. */ address private _owner; /** * @dev Address of wallet that can authorise proof of stake claims. */ address private _notary; /** * @dev Address of the token being sold. */ address payable private _tokenContract; /** * @dev UNIX timestamp of from when the tier 1 is open. */ uint256 private _tier1; /** * @dev UNIX timestamp of from when the tier 2 is open. */ uint256 private _tier2; /** * @dev UNIX timestamp of from when the tier 3 is open. */ uint256 private _tier3; /** * @dev List of all wallets that are tier1. */ mapping(address => bool) private _tier1wallets; /** * @dev Specific map of what tokenId is allowed to mint for a specific wallet. */ mapping(address => uint256[]) private _reservedTokens; /** * @dev Specific map of amount of free tokens that a specific wallet can mint. */ mapping(address => uint256) private _reservedTokenAmounts; /** * @dev A map keeping tally of total numer of tokens purchased by a wallet. */ mapping(address => uint256) private _purchasedTokens; /** * @dev Base purchase price of token in wei. */ uint256 private _tokenBasePrice; /** * @dev Stake purchase price of token in wei. */ uint256 private _tokenStakePrice; /** * @dev Claim purchase price of token in wei. */ uint256 private _tokenClaimPrice; /** * @dev Array of all tokenIds available for minting/purchasing. */ uint256[] private _allTokens; /** * @dev Mapping from token id to position in the allTokens array. */ mapping(uint256 => uint256) private _allTokensIndex; /** * @dev Boolean indicating whether to automatically withdraw payments made for minting. */ bool private _autoWithdraw; /** * @dev Capped limit of how many purchases can be made per wallet. */ uint256 private _maxPurchases; /** * @dev Boolean indicating whether _maxPurchases should be enforced. */ bool private _reserveLifted; /** * @dev Mapping of all approved functions for specific contracts. To be used for delegate calls. */ mapping(address => mapping(bytes4 => bool)) private _approvedFunctions; /** * @dev Throws if called by any account other than the owner/admin. */ modifier onlyOwner() { require(isOwner(), "CXIP: caller not an owner"); _; } /** * @dev Can be deployed with factory contracts, _admin will always be set to transaction initiator. * @param tokenContract Address of the contract that will mint the tokens. * @param notary Address of the wallet that will be used for validating stake&mint function values. * @param autoWithdraw If enabled, eth will be sent to Identity automatically on payment for minting. * @param newOwner Address of wallet/contract that will have authorization to make onlyOwner calls. */ constructor (address tokenContract, address notary, bool autoWithdraw, uint256 maxPurchases, address newOwner) { _admin = tx.origin; _owner = newOwner; _tokenContract = payable(tokenContract); _notary = notary; _autoWithdraw = autoWithdraw; _maxPurchases = maxPurchases; } /** * @notice Pay eth and buy a token. * @dev Token must first be added to list of available tokens. A non-minted token will fail this call. * @param tokenId The id of token to buy. */ function buyToken (uint256 tokenId) public payable { ISNUFFY500 snuffy = ISNUFFY500(_tokenContract); require(snuffy.exists(tokenId), "CXIP: token not minted"); require(_exists(tokenId), "CXIP: token not for sale"); require(snuffy.ownerOf(tokenId) == address(this), "CXIP: broker not owner of token"); if (_tier1wallets[msg.sender]) { require(msg.value >= _tokenClaimPrice, "CXIP: payment amount is too low"); } else { require(msg.value >= _tokenBasePrice, "CXIP: payment amount is too low"); } if (!_reserveLifted) { require(_purchasedTokens[msg.sender] < _maxPurchases, "CXIP: max allowance reached"); } _purchasedTokens[msg.sender] = _purchasedTokens[msg.sender] + 1; snuffy.safeTransferFrom(address(this), msg.sender, tokenId); _removeTokenFromAllTokensEnumeration(tokenId); if (_autoWithdraw) { _moveEth(); } } /** * @notice Claim and mint free token. * @dev Wallets needs to be added to whitelist in order for this function to work. * @param tokenId The id of token to mint. * @param tokenData The complete data for the minted token. * @param verification A signature for the tokenId and tokenData, made by a wallet authorized by Identity */ function claimAndMint (uint256 tokenId, TokenData[] calldata tokenData, Verification calldata verification) public { require(block.timestamp >= _tier1, "CXIP: too early to claim"); require(!ISNUFFY500(_tokenContract).exists(tokenId), "CXIP: token snatched"); if (_reservedTokenAmounts[msg.sender] > 0) { require(_exists(tokenId), "CXIP: token not for sale"); ISNUFFY500(_tokenContract).mint(0, tokenId, tokenData, _admin, verification, msg.sender); _reservedTokenAmounts[msg.sender] = _reservedTokenAmounts[msg.sender] - 1; _removeTokenFromAllTokensEnumeration(tokenId); } else { uint256 length = _reservedTokens[msg.sender].length; require(length > 0, "CXIP: no tokens to claim"); uint256 index = length - 1; require(_reservedTokens[msg.sender][index] == tokenId, "CXIP: not your token"); delete _reservedTokens[msg.sender][index]; _reservedTokens[msg.sender].pop(); ISNUFFY500(_tokenContract).mint(1, tokenId, tokenData, _admin, verification, msg.sender); } if (!_tier1wallets[msg.sender]) { _tier1wallets[msg.sender] = true; } if (_autoWithdraw) { _moveEth(); } } /** * @notice Call a pre-approved external function. * @dev This allows to extend the functionality of the contract, without the need of a complete re-deployment. * @param target Address of smart contract to call. * @param functionHash Function hash of the external contract function to call. * @param payload Entire payload to include in the external call. Keep in mind to not include function hash. */ function delegateApproved (address target, bytes4 functionHash, bytes calldata payload) public payable { require(_approvedFunctions[target][functionHash], "CXIP: not approved delegate call"); (bool success, bytes memory data) = target.delegatecall(abi.encodePacked(functionHash, payload)); require(success, string(data)); } /** * @notice Pay eth and mint a token. * @dev Token must first be added to list of available tokens. An already minted token will fail on mint. * @param tokenId The id of token to mint. * @param tokenData The complete data for the minted token. * @param verification A signature for the tokenId and tokenData, made by a wallet authorized by Identity */ function payAndMint (uint256 tokenId, TokenData[] calldata tokenData, Verification calldata verification) public payable { require(block.timestamp >= _tier3 || _tier1wallets[msg.sender], "CXIP: too early to buy"); require(!ISNUFFY500(_tokenContract).exists(tokenId), "CXIP: token snatched"); require(_exists(tokenId), "CXIP: token not for sale"); if (_tier1wallets[msg.sender]) { if (_purchasedTokens[msg.sender] > 0) { require(msg.value >= _tokenClaimPrice, "CXIP: payment amount is too low"); } } else { require(msg.value >= _tokenBasePrice, "CXIP: payment amount is too low"); } if (!_reserveLifted) { require(_purchasedTokens[msg.sender] < _maxPurchases, "CXIP: max allowance reached"); } _purchasedTokens[msg.sender] = _purchasedTokens[msg.sender] + 1; ISNUFFY500(_tokenContract).mint(0, tokenId, tokenData, _admin, verification, msg.sender); _removeTokenFromAllTokensEnumeration(tokenId); if (_autoWithdraw) { _moveEth(); } } /** * @notice Show proof of stake, and mint a token. * @dev First an off-chain validation of staking must be made, and signed by the notary wallet. * @param proof Signature made by the notary wallet, proving validity of stake. * @param tokens The total number of tokens staked by wallet. * @param tokenId The id of token to mint. * @param tokenData The complete data for the minted token. * @param verification A signature for the tokenId and tokenData, made by a wallet authorized by Identity */ function proofOfStakeAndMint (Verification calldata proof, uint256 tokens, uint256 tokenId, TokenData[] calldata tokenData, Verification calldata verification) public payable { require(block.timestamp >= _tier2, "CXIP: too early to stake"); require(msg.value >= _tokenStakePrice, "CXIP: payment amount is too low"); require(!ISNUFFY500(_tokenContract).exists(tokenId), "CXIP: token snatched"); require(_exists(tokenId), "CXIP: token not for sale"); bytes memory encoded = abi.encodePacked(msg.sender, tokens); require(Signature.Valid( _notary, proof.r, proof.s, proof.v, encoded ), "CXIP: invalid signature"); if (!_reserveLifted) { require(_purchasedTokens[msg.sender] < _maxPurchases, "CXIP: max allowance reached"); } _purchasedTokens[msg.sender] = _purchasedTokens[msg.sender] + 1; ISNUFFY500(_tokenContract).mint(0, tokenId, tokenData, _admin, verification, msg.sender); _removeTokenFromAllTokensEnumeration(tokenId); if (_autoWithdraw) { _moveEth(); } } /** * @notice Remove a token id from being reserved by a wallet. * @dev If you want to add a token id to for sale list, first remove it from a wallet if it has been reserved. * @param wallets Array of wallets for which to remove reserved tokens for. */ function clearReservedTokens (address[] calldata wallets) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { _reservedTokens[wallets[i]] = new uint256[](0); } } /** * @notice Can be used to bring logic from other smart contracts in (temporarily). * @dev Useful for fixing critical bugs, recovering lost tokens, and reversing accidental payments to contract. */ /** * @notice Use an external contract's logic for internal use. * @dev This will make a delegate call and use an external contract's logic, while using internal storage. * @param target Address of smart contract to call. * @param payload Bytes of the payload to send. Including the 4 byte function hash. */ function delegate (address target, bytes calldata payload) public onlyOwner { (bool success, bytes memory data) = target.delegatecall(payload); require(success, string(data)); } /** * @notice Lift the imposed purchase limits. * @dev Use this function after purchasing is opened to all with no limits. */ function liftPurchaseLimits () public onlyOwner { _reserveLifted = true; } /** * @notice Remove a token from being for sale. * @dev If you want to reserve a token, or it is no longer available, make sure to use this function and remove it. * @param tokens Array of token ids to remove from being for sale. */ function removeOpenTokens (uint256[] calldata tokens) public onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { _removeTokenFromAllTokensEnumeration(tokens[i]); } } /** * @notice Remove a token id from being reserved by a wallet. * @dev If you want to add a token id to for sale list, first remove it from a wallet if it has been reserved. * @param wallets Array of wallets for which to remove reserved tokens for. */ function removeReservedTokens (address[] calldata wallets) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { delete _reservedTokens[wallets[i]]; } } /** * @notice Configure a delegate function call for use. * @dev This will allow users to call delegate calls on external contracts to the approved function. * @param target Address of smart contract that will be called. * @param functionHash Hash of function that will be called. * @param value Boolean indicating whether to approve or deny such a call. */ function setApprovedFunction (address target, bytes4 functionHash, bool value) public onlyOwner { _approvedFunctions[target][functionHash] = value; } /** * @notice Set notary wallet address. * @dev The notary is used as a way to sign and validate proof of stake function calls. * @param notary Address of notary wallet to use. */ function setNotary (address notary) public onlyOwner { _notary = notary; } /** * @notice Add token ids that are available for purchase. * @dev These tokens can be either those that still need to be minted, or already minted tokens. * @param tokens Array of token ids to add as available for sale. */ function setOpenTokens (uint256[] calldata tokens) public onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { _addTokenToEnumeration(tokens[i]); } } /** * @notice Set prices for each tier. * @dev It is recommended to make tier 1 price lowest, and tier 3 price highest. * @param claimPrice Amount in wei for Tier 3 purchase price. * @param claimPrice Amount in wei for Tier 1 purchase price. * @param stakePrice Amount in wei for Tier 2 purchase price. */ function setPrices (uint256 basePrice, uint256 claimPrice, uint256 stakePrice) public onlyOwner { _tokenBasePrice = basePrice; _tokenClaimPrice = claimPrice; _tokenStakePrice = stakePrice; } /** * @notice Set maximum amount of purchases allowed to be made by a single wallet. * @dev This is only enforced if arePurchasesLimited is true. Claims do not count toward purchases. * @param limit Amount of token purchases that can be made. */ function setPurchaseLimit (uint256 limit) public onlyOwner { _maxPurchases = limit; } /** * @notice Set the amounts of tokens that have already been purchased by wallets. * @dev Use this to add information for sales that occurred outside of this contract. * @param wallets Array of wallets to set specific amounts for. * @param amounts Array of specific amounts to set for the wallets. */ function setPurchasedTokensAmount (address[] calldata wallets, uint256[] calldata amounts) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { _purchasedTokens[wallets[i]] = amounts[i]; } } /** * @notice Set a specific amount of tokens that can be claimed by a wallet. * @dev Use this if a wallet is allowed to claim, but no specific token ids have been assigned. * @param wallets Array of wallets to add specific amounts for. * @param amounts Array of specific amounts to set for the wallets. */ function setReservedTokenAmounts (address[] calldata wallets, uint256[] calldata amounts) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { _reservedTokenAmounts[wallets[i]] = amounts[i]; } } /** * @notice Add a token that a wallet is pre-authorized to claim and mint. * @dev This function adds to the list of claimable tokens. * @param wallets Array of wallets for which to add a token that can be claimed. * @param tokens Array of token ids that a wallet can claim. */ function setReservedTokens (address[] calldata wallets, uint256[] calldata tokens) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { _reservedTokens[wallets[i]].push (tokens[i]); } } /** * @notice Set the list of tokens that a wallet is pre-authorized to claim and mint. * @dev Resets the list of tokens for wallet to new submitted list. * @param wallets Array of wallets for which to set the list of tokens that can be claimed. * @param tokens Array of token ids that a wallet can claim. */ function setReservedTokensArrays (address[] calldata wallets, uint256[][] calldata tokens) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { _reservedTokens[wallets[i]] = tokens[i]; } } /** * @notice Set the time of each tier's activation. * @dev Can be changed at any time to push forward/back the activation times of each tier. * @param tier1 UNIX timestamp of when Tier 1 activates. * @param tier2 UNIX timestamp of when Tier 2 activates. * @param tier3 UNIX timestamp of when Tier 3 activates. */ function setTierTimes (uint256 tier1, uint256 tier2, uint256 tier3) public onlyOwner { _tier1 = tier1; _tier2 = tier2; _tier3 = tier3; } /** * @notice Set a list of wallets as VIP. * @dev This allows to have wallets skip claim process and get discounted pricing directly. * @param wallets Array of wallets to set as VIPs. */ function setVIPs (address[] calldata wallets) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { _tier1wallets[wallets[i]] = true; } } /** * @notice Transfers ownership of the smart contract. * @dev Can't be transferred to a zero address. * @param newOwner Address of new owner. */ function transferOwnership(address newOwner) public onlyOwner { require(!Address.isZero(newOwner), "CXIP: zero address"); _owner = newOwner; } /** * @notice Withdraws all smart contract ETH. * @dev Can only be called by _admin or _owner. All contract ETH is send to sender. */ function withdrawEth () public onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * @notice Call a pre-approved external function. * @dev This allows to extend the functionality of the contract, without the need of a complete re-deployment. * @param target Address of smart contract to call. * @param functionHash Function hash of the external contract function to call. * @param payload Entire payload to include in the external call. Keep in mind to not include function hash. * @return bytes Returns data of response as raw bytes. */ function delegateApprovedCall (address target, bytes4 functionHash, bytes calldata payload) public returns (bytes memory) { require(_approvedFunctions[target][functionHash], "CXIP: not approved delegate call"); (bool success, bytes memory data) = target.delegatecall(abi.encodePacked(functionHash, payload)); require(success, string(data)); return data; } /** * @notice Simple function to accept safe transfers. * @dev Token transfers that are related to the _tokenContract are automatically added to _allTokens. * @param _operator The address of the smart contract that operates the token. * @dev Since it's not being used, the _from variable is commented out to avoid compiler warnings. * @dev _tokenId Id of the token being transferred in. * @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings. * @return bytes4 Returns the interfaceId of onERC721Received. */ function onERC721Received( address payable _operator, address/* _from*/, uint256 _tokenId, bytes calldata /*_data*/ ) public returns (bytes4) { if (_operator == _tokenContract) { if (ISNUFFY500(_operator).ownerOf(_tokenId) == address(this)) { _addTokenToEnumeration (_tokenId); } } return 0x150b7a02; } /** * @notice Check if purchasing is limited. * @dev Call getPurchaseLimit if this returns true, to find out purchase limits. * @return bool Returns true if purchases are limited. */ function arePurchasesLimited () public view returns (bool) { return !_reserveLifted; } /** * @notice Get the notary wallet address. * @dev This wallet is used to sign and validate proof of stake wallets. * @return address Returns address of wallet that signs the proof of stake messages. */ function getNotary () public view returns (address) { return _notary; } /** * @notice Get the purchase prices for each tier. * @dev VIP wallets that are claiming tokens are not charged a fee. * @return basePrice Price of Tier 3 purchases. * @return claimPrice Price of Tier 1 purchases. * @return stakePrice Price of Tier 2 purchases. */ function getPrices () public view returns (uint256 basePrice, uint256 claimPrice, uint256 stakePrice) { basePrice = _tokenBasePrice; claimPrice = _tokenClaimPrice; stakePrice = _tokenStakePrice; } /** * @notice Get maximum number of tokens that can be purchased. * @dev Used in conjunction with arePurchasesLimited function. * @return uint256 Returns the maximum amount of tokens that can be purchased at the moment. */ function getPurchaseLimit() public view returns (uint256) { return _maxPurchases; } /** * @notice Check how many tokens have been purchased by a wallet. * @dev Used in conjunction with arePurchasesLimited function. * @param wallet Address of wallet in question. * @return uint256 Returns number of tokens that a wallet has already claimed/minted. */ function getPurchasedTokensAmount (address wallet) public view returns (uint256) { return _purchasedTokens[wallet]; } /** * @notice Check how many free token claims are available for a wallet. * @dev These are not token id locked claims. * @param wallet Address of wallet in question. * @return uint256 Returns the number of free claims available. */ function getReservedTokenAmounts(address wallet) public view returns (uint256) { return _reservedTokenAmounts[wallet]; } /** * @notice Check if there are any tokens specifically reserved for a wallet. * @dev Helpful function for front-end UI development. * @param wallet Address of the wallet to check. * @return uint256[] Returns an array of token ids that are reserved for that wallet to claim. */ function getReservedTokens(address wallet) public view returns (uint256[] memory) { return _reservedTokens[wallet]; } /** * @notice Get the timestamps for when each tier is activated. * @dev Check if a tier is active, meaning that relevant functions will work. * @return tier1 UNIX timestamp of when Tier 1 activates. * @return tier2 UNIX timestamp of when Tier 2 activates. * @return tier3 UNIX timestamp of when Tier 3 activates. */ function getTierTimes () public view returns (uint256 tier1, uint256 tier2, uint256 tier3) { tier1 = _tier1; tier2 = _tier2; tier3 = _tier3; } /** * @notice Check if the sender is the owner. * @dev The owner could also be the admin. * @return bool Returns true if owner. */ function isOwner() public view returns (bool) { return (msg.sender == _owner || msg.sender == _admin); } /** * @notice Check if a wallet is VIP. * @dev Any wallet that was whitelisted for specific tokenId or amount, is marked as VIP after first claim. * @param wallet Address of wallet in question. * @return bool Returns true if wallet is VIP. */ function isVIP (address wallet) public view returns (bool) { return _tier1wallets[wallet]; } /** * @notice Gets the owner's address. * @dev _owner is first set in init. * @return address Returns the address of owner. */ function owner() public view returns (address) { return _owner; } /** * @notice Get token by index. * @dev Used in conjunction with totalSupply function to iterate over all tokens in collection. * @param index Index of token in array. * @return uint256 Returns the token id of token located at that index. */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "CXIP: index out of bounds"); return _allTokens[index]; } /** * @notice Get x amount of token ids, starting from index x. * @dev Can be used as pagination, to not have to get each token id through separate call. * @param start Index from which to start from. * @param length Total number of items to read in array. * @return tokens Returns an array of token ids. */ function tokensByChunk(uint256 start, uint256 length) public view returns (uint256[] memory tokens) { if (start + length > totalSupply()) { length = totalSupply() - start; } tokens = new uint256[](length); for (uint256 i = 0; i < length; i++) { tokens[i] = _allTokens[start + i]; } } /** * @notice Total amount of tokens available for sale. * @dev Does not include/count reserved tokens. * @return uint256 Returns the total number of available tokens. */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @notice Shows the interfaces the contracts support * @dev Must add new 4 byte interface Ids here to acknowledge support * @param interfaceId ERC165 style 4 byte interfaceId. * @return bool True if supported. */ function supportsInterface(bytes4 interfaceId) external pure returns (bool) { if ( interfaceId == 0x01ffc9a7 || // ERC165 interfaceId == 0x150b7a02 // ERC721TokenReceiver ) { return true; } else { return false; } } /** * @dev Add a newly added token into managed list of tokens. * @param tokenId Id of token to add. */ function _addTokenToEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Transfer all smart contract ETH to token contract's Identity contract. */ function _moveEth() internal { uint256 amount = address(this).balance; payable(ISNUFFY500(_tokenContract).getIdentity()).transfer(amount); } /** * @dev Remove a token from managed list of tokens. * @param tokenId Id of token to remove. */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; _allTokensIndex[lastTokenId] = tokenIndex; delete _allTokensIndex[tokenId]; delete _allTokens[lastTokenIndex]; _allTokens.pop(); } /** * @notice Checks if the token is in our possession. * @dev We check that returned value actually matches the tokenId, to avoid zero index issue. * @param tokenId The token in question. * @return bool Returns true if token exists. */ function _exists(uint256 tokenId) internal view returns (bool) { return _allTokens[_allTokensIndex[tokenId]] == tokenId; } } /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function isZero(address account) internal pure returns (bool) { return (account == address(0)); } } /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ library Signature { function Derive( bytes32 r, bytes32 s, uint8 v, bytes memory encoded ) internal pure returns ( address derived1, address derived2, address derived3, address derived4 ) { bytes32 encoded32; assembly { encoded32 := mload(add(encoded, 32)) } derived1 = ecrecover(encoded32, v, r, s); derived2 = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", encoded32)), v, r, s); encoded32 = keccak256(encoded); derived3 = ecrecover(encoded32, v, r, s); encoded32 = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", encoded32)); derived4 = ecrecover(encoded32, v, r, s); } function PackMessage(bytes memory encoded, bool geth) internal pure returns (bytes32) { bytes32 hash = keccak256(encoded); if (geth) { hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } return hash; } function Valid( address target, bytes32 r, bytes32 s, uint8 v, bytes memory encoded ) internal pure returns (bool) { bytes32 encoded32; address derived; if (encoded.length == 32) { assembly { encoded32 := mload(add(encoded, 32)) } derived = ecrecover(encoded32, v, r, s); if (target == derived) { return true; } derived = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", encoded32)), v, r, s); if (target == derived) { return true; } } bytes32 hash = keccak256(encoded); derived = ecrecover(hash, v, r, s); if (target == derived) { return true; } hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); derived = ecrecover(hash, v, r, s); return target == derived; } } /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ struct Verification { bytes32 r; bytes32 s; uint8 v; } /*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ _____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_ ___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_ __/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__ _\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____ _\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________ __\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________ ____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________ _______\/////////__\///_______\///__\///////////__\///____________*/ struct TokenData { bytes32 payloadHash; Verification payloadSignature; address creator; bytes32 arweave; bytes11 arweave2; bytes32 ipfs; bytes14 ipfs2; } /* O _ ---\ _|.|_ /--- ---| | |--- |_/ \_| | | | | |___| | | / \ SNUFFY 500 */ interface ISNUFFY500 { function mint(uint256 state, uint256 tokenId, TokenData[] memory tokenData, address signer, Verification memory verification, address recipient) external; function safeTransferFrom(address from, address to, uint256 tokenId) external; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) external; function balanceOf(address wallet) external view returns (uint256); function exists(uint256 tokenId) external view returns (bool); function getIdentity() external view returns (address); function ownerOf(uint256 tokenId) external view returns (address); }
Add a newly added token into managed list of tokens. tokenId Id of token to add./
function _addTokenToEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
9,978,709
./full_match/5/0xDd075Ee118E993A9C18806561635a5a74974F556/sources/project_/contracts/MetaWinnersDAC.sol
Overrides {BatchReveal._metadataIdsStartFromOne} to return True (when it does, revealed IDs will be offset and start from 1 - instead of 0)/
function _metadataIdsStartFromOne() internal pure override returns(bool){ return true; }
1,879,257
./full_match/8453/0xEF153cb7bfc04c657Cb7f582C7411556320098B9/sources/contracts/farm/SynthChef.sol
Pay or lockup pending Synth.
function payOrLockupPendingSynth(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.nextHarvestUntil == 0 && block.timestamp >= startTimestamp) { user.nextHarvestUntil = block.timestamp + pool.harvestInterval; } if (user.nextHarvestUntil != 0 && pool.harvestInterval == 0) { user.nextHarvestUntil = 0; } uint256 pending = ((user.amount * pool.accSynthPerShare) / ACC_TOKEN_PRECISION) - user.rewardDebt; if (canHarvest(_pid, msg.sender)) { if (pending > 0 || user.rewardLockedUp > 0) { uint256 pendingRewards = pending + user.rewardLockedUp; totalLockedUpRewards -= user.rewardLockedUp; user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp + pool.harvestInterval; uint256 xSynthAmount = (pendingRewards * xSynthRate) / 100; uint256 synthAmount = pendingRewards - xSynthAmount; if (xSynthAmount > 0) { xSynth.convertTo(xSynthAmount, msg.sender); emit XRewardPaid(msg.sender, _pid, xSynthAmount); } if (synthAmount > 0) { safeSynthTransfer(msg.sender, synthAmount); emit RewardPaid(msg.sender, _pid, synthAmount); } } totalLockedUpRewards += pending; user.rewardLockedUp += pending; emit RewardLockedUp(msg.sender, _pid, pending); } }
11,558,357
pragma solidity ^0.4.11; import "./Owned.sol"; contract CurrencyHedge is Owned { struct Hedge { address beneficiary; uint hedgeStart; // Seconds in Unix Epoch (since Jan 1, 1970) uint hedgeEnd; // Seconds in Unix Epoch bytes3 homeCurr; // Denoted with three letters (e.g. USD, EUR) bytes3 hedgeCurr; // Rates will be evaluated up to 5 decimal points, and so must be // multiplied by 10^5 to be stored as an integer value. uint64 refRate; bytes32 instID; // Institution identifier bytes32 acctID; // ID of account associated with institution bool active; // Hedge contract state (active or expired?) } struct Transaction { // This struct will eventually need a way to check that the purchase made // by the client is actually covered by the hedge (e.g. client made the // purchase in Thailand for a Thai hedge and not in, say, New Zealand) uint timeStamp; // Seconds in Unix Epoch uint64 txValue; // Transaction value in home currency uint64 rateDiff; // Difference between spot exchange rate at time of transaction and hedge's reference rate } // Create a global list of all hedges // NOTE: This implies that hedgeTx will also be public, which it probably shouldn't be Hedge[] public allHedges; // Solidity cannot return structs, and can only return arrays of addresses, bools, or uints mapping (address => uint256[]) private hedgeIndices; // Reverse mapping of indices to addresses for easy verification mapping (uint256 => address) private hedgeBeneficiaries; // Mapping of Hedge indices to arrays of Transactions. This must be used because Solidity does weird // things when a struct array is nested inside another struct // Refer to https://ethereum.stackexchange.com/questions/3525/how-to-initialize-empty-struct-array-in-new-struct mapping (uint256 => Transaction[]) private allTx; // CurrencyHedge: Contract creator. function CurrencyHedge() { owner = msg.sender; } // addHedge: Add a new hedge to the book function addHedge(address _beneficiary, uint _hedgeStart, uint _hedgeEnd, bytes3 _homeCurr, bytes3 _hedgeCurr, uint64 _refRate, bytes32 _instID, bytes32 _acctID) public onlyOwner { require(_hedgeEnd - _hedgeStart >= 604800); // Enforce minimum hedge period of 7 days = 604,800 seconds // Create a new hedge and populate the information. Hedge memory newHedge = Hedge(_beneficiary, _hedgeStart, _hedgeEnd, _homeCurr, _hedgeCurr, _refRate, _instID, _acctID, false); // Add the hedge to the global list, and associate the index of the hedge with the beneficiary allHedges.push(newHedge); uint newIndex = allHedges.length - 1; hedgeIndices[_beneficiary].push(newIndex); hedgeBeneficiaries[newIndex] = _beneficiary; } // getHedgeIndices: Retrieve a list of indices of the allHedges array associated with a particular beneficiary's // Refer to https://ethereum.stackexchange.com/questions/3589/how-can-i-return-an-array-of-struct-from-a-function function getHedgeIndices(address _beneficiary) public onlyOwner returns (uint256[]) { return hedgeIndices[_beneficiary]; } // getNumberOfTx: Retrieve the number of transactions currently associated with a given hedge function getNumberOfTx(uint _index) public onlyOwner returns (uint) { return allTx[_index].length; } // activateHedge: Activate a hedge and allow transactions to be recorded to it function activateHedge(address _beneficiary, uint256 _index) public onlyOwner { require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated require(!allHedges[_index].active); // Check that the hedge is currently inactive // This should be verified outside of the contract. 'now' is an alias for // block.timestamp, not current time require(allHedges[_index].hedgeEnd < now); // Don't reactivate a dead hedge require(allHedges[_index].hedgeStart >= now); // Don't prematurely activate a hedge allHedges[_index].active = true; } // deactivateHedge: Deactivate a hedge and prevent any new data from being added function deactivateHedge(address _beneficiary, uint256 _index) public onlyOwner { require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated require(allHedges[_index].active); // Check that the hedge is currently active // This should be verified outside of the contract. 'now' is an alias for // block.timestamp, not current time require(allHedges[_index].hedgeEnd >= now); // Don't prematurely deactivate a hedge allHedges[_index].active = false; } // recordTransaction: Add a transaction record to a particular hedge function recordTransaction(address _beneficiary, uint256 _index, uint64 _timeStamp, uint64 _txValue, uint64 _spotRate) public onlyOwner { require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated require(allHedges[_index].active); // Check that the hedge is currently inactive // This should be verified outside of the contract. 'now' is an alias for // block.timestamp, not current time require(allHedges[_index].hedgeEnd <= now); Transaction memory newTx = Transaction(_timeStamp, _txValue, _spotRate - allHedges[_index].refRate); allTx[_index].push(newTx); } // endContract: Close out the hedge and pay whatever is needed to the beneficiary function endContract(address _beneficiary, uint256 _index) public payable onlyOwner { require(hedgeBeneficiaries[_index] == _beneficiary); // Check that the specified index and beneficiary are associated require(!allHedges[_index].active); // Check that the hedge is currently inactive require(allTx[_index].length > 0); // Check that the list of transactions is greater than zero // Calculate the value of the payout to the beneficiary uint totalPayout = 0; for (uint256 i = 0; i < allTx[_index].length; i++) { if (allTx[_index][i].rateDiff > 0) totalPayout += allTx[_index][i].txValue * allTx[_index][i].rateDiff; } // Deactivate the hedge deactivateHedge(_beneficiary, _index); _beneficiary.transfer(totalPayout); } }
recordTransaction: Add a transaction record to a particular hedge This should be verified outside of the contract. 'now' is an alias for block.timestamp, not current time
function recordTransaction(address _beneficiary, uint256 _index, uint64 _timeStamp, uint64 _txValue, uint64 _spotRate) public onlyOwner { require(allHedges[_index].hedgeEnd <= now); Transaction memory newTx = Transaction(_timeStamp, _txValue, _spotRate - allHedges[_index].refRate); allTx[_index].push(newTx); }
15,780,873
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * Extremely simple, NOT FOR PRODUCTION, simulation for supply chain shipment notifications. * * The mock shipment scenario is that there are several shipping center locations registered as "suppliers". * Each supplier is registered by the authority that owns this contract. Suppliers record receipt of shipment * to show progress along a route to a final destination. * * Anyone can witness seeing a package along the route to verify that a supplier did, in fact, receive shipment. * Obviously the more witnesses there are, the more credible the supplier record. Witnesses can only witness a shipment * once for any item. * * There are many holes in this scenario and should never be used for real world shipment tracking. * Some things that are glossed over or missing in this contract: * - Shipment details would need to be recorded first, including expected checkpoints along a route * - Supplier checkpoints would probably stake ETH or tokens as insurance that they are accurately recording shipment receipts * - While witnesses could be used to slash a supplier's stack, they could be gamed through a sybil attack in collusion with a supplier * - An obvious verification check would be a supplier later in the route recording receipt. The previous supplier not having recorded shipment * could be slashed in that case. Suppliers, however, could collude to avoid slashing. */ contract SupplyChainDemo { bytes32 constant NULL = ""; //emitted when a new supplier address is registered event SupplierRegistered(uint256 supplierID, address supplier, string details); //emitted when a supplier receives shipment event ShipmentReceived(uint256 indexed itemID, address indexed receiver, bytes32 hash, string metadata); //emitted when anyone witnesses receipt of shipment along a supply route event ShipmentWitnessed(uint256 indexed itemID, uint256 supplierID, bytes32 witnessNameHash); //contract owner address public owner; //unique ID for each supplier uint256 supplierID; //record for a specific supplier. struct SupplierRecord { bytes32 supplierMetadata; uint256 witnessCount; } //record from a witness for a specific supplier struct WitnessRecord { bytes32 nameHash; uint256 supplier; } //record of shipment receipt struct ShipmentTracking { //information for each supplier mapping(uint256 => SupplierRecord) supplierRecords; //record that a particular address witnessed receipt from a supplier. Addresses can only witness once. //This is open to sybil attack. mapping(address => WitnessRecord) witnessRecords; } //suppliers keyed by their public address mapping(address => uint256) public suppliersByAddress; //all shipment metadata received keyted by itemID mapping(uint256 => ShipmentTracking) receivedShipments; //create contract constructor() public { owner = msg.sender; addSupplier(msg.sender, "owner"); } //only allowed if a registered supplier calls function modifier onlySuppliers() { if(suppliersByAddress[msg.sender] != 0x0 || msg.sender == owner) _; } //only allowed by contract owner modifier ownerOnly() { if(msg.sender == owner) _; } /** * Authorize a supplier address so they can record shipment details */ function addSupplier(address supplier, string memory details) public ownerOnly { uint256 id = supplierID + 1; supplierID++; suppliersByAddress[supplier] = id; emit SupplierRegistered(id, supplier, details); } /** * Record shipment details. Only suppliers can call this function */ function recordShipmentReceived(uint256 itemID, string memory metadata) public { require(msg.sender == owner || suppliersByAddress[msg.sender] != 0x0, "Unauthorized to record shipments"); bytes32 hash = keccak256(bytes(metadata)); uint256 supplier = suppliersByAddress[msg.sender]; ShipmentTracking storage history = receivedShipments[itemID]; SupplierRecord storage rec = history.supplierRecords[supplier]; require(rec.supplierMetadata == NULL, "Shipment already received by supplier"); rec.supplierMetadata = hash; emit ShipmentReceived(itemID, msg.sender, hash, metadata); } /** * Witness the receipt of shipment by a supplier */ function witnessShipment(uint256 itemID, uint256 _supplierID, bytes32 witnessNameHash) public { ShipmentTracking storage history = receivedShipments[itemID]; WitnessRecord storage wit = history.witnessRecords[msg.sender]; require(wit.nameHash == NULL, "Witness already registered for item"); SupplierRecord storage rec = history.supplierRecords[_supplierID]; rec.witnessCount++; wit.nameHash = witnessNameHash; wit.supplier = _supplierID; emit ShipmentWitnessed(itemID, _supplierID, witnessNameHash); } /** * Get any recorded metadata for a shipment by a supplier */ function getSupplierMetadata(uint256 itemID, uint256 _supplierID) public view returns(bytes32) { ShipmentTracking storage history = receivedShipments[itemID]; SupplierRecord storage rec = history.supplierRecords[_supplierID]; return rec.supplierMetadata; } /** * Get number of witnesses for a shipment and supplier */ function getSupplierWitnessCount(uint256 itemID, uint256 _supplierID) public view returns(uint256) { ShipmentTracking storage history = receivedShipments[itemID]; SupplierRecord storage rec = history.supplierRecords[_supplierID]; return rec.witnessCount; } /** * Get recorded witness data for an item and specific witness address. */ function getWitnessInfo(uint256 itemID, address witness) public view returns(bytes32, uint256) { ShipmentTracking storage history = receivedShipments[itemID]; WitnessRecord storage rec = history.witnessRecords[witness]; return (rec.nameHash, rec.supplier); } }
Get number of witnesses for a shipment and supplier/
function getSupplierWitnessCount(uint256 itemID, uint256 _supplierID) public view returns(uint256) { ShipmentTracking storage history = receivedShipments[itemID]; SupplierRecord storage rec = history.supplierRecords[_supplierID]; return rec.witnessCount; }
15,805,978
pragma solidity ^0.4.19; // /* CONTRACT */ contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // END_OF_contract_SafeMath //_________________________________________________________ // /* INTERFACES */ // interface tokenRecipient { function receiveApproval(address _from, uint256 _tokenAmountApproved, address tokenMacroansy, bytes _extraData) public returns(bool success); } //________________________________________________________ // interface ICO { function buy( uint payment, address buyer, bool isPreview) public returns(bool success, uint amount); function redeemCoin(uint256 amount, address redeemer, bool isPreview) public returns (bool success, uint redeemPayment); function sell(uint256 amount, address seller, bool isPreview) public returns (bool success, uint sellPayment ); function paymentAction(uint paymentValue, address beneficiary, uint paytype) public returns(bool success); function recvShrICO( address _spender, uint256 _value, uint ShrID) public returns (bool success); function burn( uint256 value, bool unburn, uint totalSupplyStart, uint balOfOwner) public returns( bool success); function getSCF() public returns(uint seriesCapFactorMulByTenPowerEighteen); function getMinBal() public returns(uint minBalForAccnts_ ); function getAvlShares(bool show) public returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding); } //_______________________________________________________ // interface Exchg{ function sell_Exchg_Reg( uint amntTkns, uint tknPrice, address seller) public returns(bool success); function buy_Exchg_booking( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment ) public returns(bool success); function buy_Exchg_BkgChk( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment) public returns(bool success); function updateSeller( address seller, uint tknsApr, address buyer, uint payment) public returns(bool success); function getExchgComisnMulByThousand() public returns(uint exchgCommissionMulByThousand_); function viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_); } //_________________________________________________________ // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md /* CONTRACT */ // contract TokenERC20Interface { function totalSupply() public constant returns (uint coinLifeTimeTotalSupply); function balanceOf(address tokenOwner) public constant returns (uint coinBalance); function allowance(address tokenOwner, address spender) public constant returns (uint coinsRemaining); 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); } //END_OF_contract_ERC20Interface //_________________________________________________________________ /* CONTRACT */ /** * COPYRIGHT Macroansy * http://www.macroansy.org */ contract TokenMacroansy is TokenERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals = 18; // address internal owner; address private beneficiaryFunds; // uint256 public totalSupply; uint256 internal totalSupplyStart; // mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping( address => bool) internal frozenAccount; // mapping(address => uint) private msgSndr; // address tkn_addr; address ico_addr; address exchg_addr; // uint256 internal allowedIndividualShare; uint256 internal allowedPublicShare; // //uint256 internal allowedFounderShare; //uint256 internal allowedPOOLShare; //uint256 internal allowedVCShare; //uint256 internal allowedColdReserve; //_________________________________________________________ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint amount); event UnBurn(address indexed from, uint amount); event FundOrPaymentTransfer(address beneficiary, uint amount); event FrozenFunds(address target, bool frozen); event BuyAtMacroansyExchg(address buyer, address seller, uint tokenAmount, uint payment); //_________________________________________________________ // //CONSTRUCTOR /* Initializes contract with initial supply tokens to the creator of the contract */ function TokenMacroansy() public { owner = msg.sender; beneficiaryFunds = owner; //totalSupplyStart = initialSupply * 10** uint256(decimals); totalSupplyStart = 3999 * 10** uint256(decimals); totalSupply = totalSupplyStart; // balanceOf[msg.sender] = totalSupplyStart; Transfer(address(0), msg.sender, totalSupplyStart); // name = "TokenMacroansy"; symbol = "$BEE"; // allowedIndividualShare = uint(1)*totalSupplyStart/100; allowedPublicShare = uint(20)* totalSupplyStart/100; // //allowedFounderShare = uint(20)*totalSupplyStart/100; //allowedPOOLShare = uint(9)* totalSupplyStart/100; //allowedColdReserve = uint(41)* totalSupplyStart/100; //allowedVCShare = uint(10)* totalSupplyStart/100; } //_________________________________________________________ modifier onlyOwner { require(msg.sender == owner); _; } function wadmin_transferOr(address _Or) public onlyOwner { owner = _Or; } //_________________________________________________________ /** * @notice Show the `totalSupply` for this Token contract */ function totalSupply() constant public returns (uint coinLifeTimeTotalSupply) { return totalSupply ; } //_________________________________________________________ /** * @notice Show the `tokenOwner` balances for this contract * @param tokenOwner the token owners address */ function balanceOf(address tokenOwner) constant public returns (uint coinBalance) { return balanceOf[tokenOwner]; } //_________________________________________________________ /** * @notice Show the allowance given by `tokenOwner` to the `spender` * @param tokenOwner the token owner address allocating allowance * @param spender the allowance spenders address */ function allowance(address tokenOwner, address spender) constant public returns (uint coinsRemaining) { return allowance[tokenOwner][spender]; } //_________________________________________________________ // function wadmin_setContrAddr(address icoAddr, address exchAddr ) public onlyOwner returns(bool success){ tkn_addr = this; ico_addr = icoAddr; exchg_addr = exchAddr; return true; } // function _getTknAddr() internal returns(address tkn_ma_addr){ return(tkn_addr); } function _getIcoAddr() internal returns(address ico_ma_addr){ return(ico_addr); } function _getExchgAddr() internal returns(address exchg_ma_addr){ return(exchg_addr); } // _getTknAddr(); _getIcoAddr(); _getExchgAddr(); // address tkn_addr; address ico_addr; address exchg_addr; //_________________________________________________________ // /* Internal transfer, only can be called by this contract */ // function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require(!frozenAccount[_from]); require(!frozenAccount[_to]); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require (balanceOf[_from] >= _valueA); require (balanceOf[_to] + _valueA > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = safeSub(balanceOf[_from], _valueA); balanceOf[_to] = safeAdd(balanceOf[_to], _valueA); Transfer(_from, _to, _valueA); _valueA = 0; assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } //________________________________________________________ /** * Transfer tokens * * @notice Allows to Send Coins to other accounts * @param _to The address of the recipient of coins * @param _value The amount of coins to send */ function transfer(address _to, uint256 _value) public returns(bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _to, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueTemp = valtmp; valtmp = 0; _transfer(msg.sender, _to, _valueTemp); _valueTemp = 0; return true; } //_________________________________________________________ /** * Transfer tokens from other address * * @notice sender can set an allowance for another contract, * @notice and the other contract interface function receiveApproval * @notice can call this funtion for token as payment and add further coding for service. * @notice please also refer to function approveAndCall * @notice Send `_value` tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient of coins * @param _value The amount coins to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require(_valueA <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _valueA); _transfer(_from, _to, _valueA); _valueA = 0; return true; } //_________________________________________________________ /** * Set allowance for other address * * @notice Allows `_spender` to spend no more than `_value` coins from your account * @param _spender The address authorized to spend * @param _value The max amount of coins allocated to spender */ function approve(address _spender, uint256 _value) public returns (bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _spender, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; allowance[msg.sender][_spender] = _valueA; Approval(msg.sender, _spender, _valueA); _valueA =0; return true; } //_________________________________________________________ /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` coins in from your account * * @param _spender The address authorized to spend * @param _value the max amount of coins the spender can spend * @param _extraData some extra information to send to the spender contracts */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; if (approve(_spender, _valueA)) { spender.receiveApproval(msg.sender, _valueA, this, _extraData); } _valueA = 0; return true; } //_________________________________________________________ // /** * @notice `freeze` Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function wadmin_freezeAccount(address target, bool freeze) onlyOwner public returns(bool success) { frozenAccount[target] = freeze; FrozenFunds(target, freeze); return true; } //________________________________________________________ // function _safeTransferTkn( address _from, address _to, uint amount) internal returns(bool sucsTrTk){ uint tkA = amount; uint tkAtemp = tkA; tkA = 0; _transfer(_from, _to, tkAtemp); tkAtemp = 0; return true; } //_________________________________________________________ // function _safeTransferPaymnt( address paymentBenfcry, uint payment) internal returns(bool sucsTrPaymnt){ uint pA = payment; uint paymentTemp = pA; pA = 0; paymentBenfcry.transfer(paymentTemp); FundOrPaymentTransfer(paymentBenfcry, paymentTemp); paymentTemp = 0; return true; } //_________________________________________________________ // function _safePaymentActionAtIco( uint payment, address paymentBenfcry, uint paytype) internal returns(bool success){ // payment req to ico uint Pm = payment; uint PmTemp = Pm; Pm = 0; ICO ico = ICO(_getIcoAddr()); // paytype 1 for redeempayment and 2 for sell payment bool pymActSucs = ico.paymentAction( PmTemp, paymentBenfcry, paytype); require(pymActSucs == true); PmTemp = 0; return true; } //_________________________________________________________ /* @notice Allows to Buy ICO tokens directly from this contract by sending ether */ function buyCoinsAtICO() payable public returns(bool success) { msgSndr[msg.sender] = msg.value; ICO ico = ICO(_getIcoAddr() ); require( msg.value > 0 ); // buy exe at ico bool icosuccess; uint tknsBuyAppr; (icosuccess, tknsBuyAppr) = ico.buy( msg.value, msg.sender, false); require( icosuccess == true ); // tkn transfer bool sucsTrTk = _safeTransferTkn( owner, msg.sender, tknsBuyAppr); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return (true) ; } //_____________________________________________________________ // /* @notice Allows anyone to preview a Buy of ICO tokens before an actual buy */ function buyCoinsPreview(uint myProposedPaymentInWEI) public view returns(bool success, uint tokensYouCanBuy, uint yourSafeMinBalReqdInWEI) { uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = payment; success = false; ICO ico = ICO(_getIcoAddr() ); tokensYouCanBuy = 0; bool icosuccess; (icosuccess, tokensYouCanBuy) = ico.buy( payment, msg.sender, true); msgSndr[msg.sender] = 0; return ( icosuccess, tokensYouCanBuy, ico.getMinBal()) ; } //_____________________________________________________________ /** * @notice Allows Token owners to Redeem Tokens to this Contract for its value promised */ function redeemCoinsToICO( uint256 amountOfCoinsToRedeem) public returns (bool success ) { uint amount = amountOfCoinsToRedeem; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr()); // redeem exe at ico bool icosuccess ; uint redeemPaymentValue; (icosuccess , redeemPaymentValue) = ico.redeemCoin( amount, msg.sender, isPreview); require( icosuccess == true); require( _getIcoAddr().balance >= safeAdd( ico.getMinBal() , redeemPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false) { // transfer tkns sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment req to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = redeemPaymentValue; pymActSucs = _safePaymentActionAtIco( redeemPaymentValue, msg.sender, 1); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return (true); } //_________________________________________________________ /** * @notice Allows Token owners to Sell Tokens directly to this Contract * */ function sellCoinsToICO( uint256 amountOfCoinsToSell ) public returns (bool success ) { uint amount = amountOfCoinsToSell; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr() ); // sell exe at ico bool icosuccess; uint sellPaymentValue; ( icosuccess , sellPaymentValue) = ico.sell( amount, msg.sender, isPreview); require( icosuccess == true ); require( _getIcoAddr().balance >= safeAdd(ico.getMinBal() , sellPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false){ // token transfer sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment request to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = sellPaymentValue; pymActSucs = _safePaymentActionAtIco( sellPaymentValue, msg.sender, 2); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return ( true); } //________________________________________________________ /** * @notice a sellers allowed limits in holding ico tokens is checked */ // function _chkSellerLmts( address seller, uint amountOfCoinsSellerCanSell) internal returns(bool success){ uint amountTkns = amountOfCoinsSellerCanSell; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= balanceOf[seller] && balanceOf[seller] <= safeDiv(allowedIndividualShare*seriesCapFactor,10**18) ){ success = true; } return success; } // bool sucsSlrLmt = _chkSellerLmts( address seller, uint amountTkns); //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens is checked */ function _chkBuyerLmts( address buyer, uint amountOfCoinsBuyerCanBuy) internal returns(bool success){ uint amountTkns = amountOfCoinsBuyerCanBuy; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= safeSub( safeDiv(allowedIndividualShare*seriesCapFactor,10**18), balanceOf[buyer] )) { success = true; } return success; } //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens along with financial capacity to buy is checked */ function _chkBuyerLmtsAndFinl( address buyer, uint amountTkns, uint priceOfr) internal returns(bool success){ success = false; // buyer limits bool sucs1 = false; sucs1 = _chkBuyerLmts( buyer, amountTkns); // buyer funds ICO ico = ICO( _getIcoAddr() ); bool sucs2 = false; if( buyer.balance >= safeAdd( safeMul(amountTkns , priceOfr) , ico.getMinBal() ) ) sucs2 = true; if( sucs1 == true && sucs2 == true) success = true; return success; } //_________________________________________________________ // function _slrByrLmtChk( address seller, uint amountTkns, uint priceOfr, address buyer) internal returns(bool success){ // seller limits check bool successSlrl; (successSlrl) = _chkSellerLmts( seller, amountTkns); // buyer limits check bool successByrlAFinl; (successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr); require( successSlrl == true && successByrlAFinl == true); return true; } //___________________________________________________________________ /** * @notice allows a seller to formally register his sell offer at ExchangeMacroansy */ function sellBkgAtExchg( uint amountOfCoinsOffer, uint priceOfOneCoinInWEI) public returns(bool success){ uint amntTkns = amountOfCoinsOffer ; uint tknPrice = priceOfOneCoinInWEI; // seller limits bool successSlrl; (successSlrl) = _chkSellerLmts( msg.sender, amntTkns); require(successSlrl == true); msgSndr[msg.sender] = amntTkns; // bkg registration at exchange Exchg em = Exchg(_getExchgAddr()); bool emsuccess; (emsuccess) = em.sell_Exchg_Reg( amntTkns, tknPrice, msg.sender ); require(emsuccess == true ); msgSndr[msg.sender] = 0; return true; } //_________________________________________________________ // /** * @notice function for booking and locking for a buy with respect to a sale offer registered * @notice after booking then proceed for payment using func buyCoinsAtExchg * @notice payment booking value and actual payment value should be exact */ function buyBkgAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint myProposedPaymentInWEI) public returns(bool success){ uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = amountTkns; // seller buyer limits check bool sucsLmt = _slrByrLmtChk( seller, amountTkns, priceOfr, msg.sender); require(sucsLmt == true); // booking at exchange Exchg em = Exchg(_getExchgAddr()); bool emBkgsuccess; (emBkgsuccess)= em.buy_Exchg_booking( seller, amountTkns, priceOfr, msg.sender, payment); require( emBkgsuccess == true ); msgSndr[msg.sender] = 0; return true; } //________________________________________________________ /** * @notice for buyingCoins at ExchangeMacroansy * @notice please first book the buy through function_buy_Exchg_booking */ // function buyCoinsAtExchg( address seller, uint amountTkns, uint priceOfr) payable public returns(bool success) { function buyCoinsAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI) payable public returns(bool success) { uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; require( msg.value > 0 && msg.value <= safeMul(amountTkns, priceOfr ) ); msgSndr[msg.sender] = amountTkns; // calc tokens that can be bought uint tknsBuyAppr = safeDiv(msg.value , priceOfr); // check buyer booking at exchange Exchg em = Exchg(_getExchgAddr()); bool sucsBkgChk = em.buy_Exchg_BkgChk(seller, amountTkns, priceOfr, msg.sender, msg.value); require(sucsBkgChk == true); // update seller reg and buyer booking at exchange msgSndr[msg.sender] = tknsBuyAppr; bool emUpdateSuccess; (emUpdateSuccess) = em.updateSeller(seller, tknsBuyAppr, msg.sender, msg.value); require( emUpdateSuccess == true ); // token transfer in this token contract bool sucsTrTkn = _safeTransferTkn( seller, msg.sender, tknsBuyAppr); require(sucsTrTkn == true); // payment to seller bool sucsTrPaymnt; sucsTrPaymnt = _safeTransferPaymnt( seller, safeSub( msg.value , safeDiv(msg.value*em.getExchgComisnMulByThousand(),1000) ) ); require(sucsTrPaymnt == true ); // BuyAtMacroansyExchg(msg.sender, seller, tknsBuyAppr, msg.value); //event msgSndr[msg.sender] = 0; return true; } //___________________________________________________________ /** * @notice Fall Back Function, not to receive ether directly and/or accidentally * */ function () public payable { if(msg.sender != owner) revert(); } //_________________________________________________________ /* * @notice Burning tokens ie removing tokens from the formal total supply */ function wadmin_burn( uint256 value, bool unburn) onlyOwner public returns( bool success ) { msgSndr[msg.sender] = value; ICO ico = ICO( _getIcoAddr() ); if( unburn == false) { balanceOf[owner] = safeSub( balanceOf[owner] , value); totalSupply = safeSub( totalSupply, value); Burn(owner, value); } if( unburn == true) { balanceOf[owner] = safeAdd( balanceOf[owner] , value); totalSupply = safeAdd( totalSupply , value); UnBurn(owner, value); } bool icosuccess = ico.burn( value, unburn, totalSupplyStart, balanceOf[owner] ); require( icosuccess == true); return true; } //_________________________________________________________ /* * @notice Withdraw Payments to beneficiary * @param withdrawAmount the amount withdrawn in wei */ function wadmin_withdrawFund(uint withdrawAmount) onlyOwner public returns(bool success) { success = _withdraw(withdrawAmount); return success; } //_________________________________________________________ /*internal function can called by this contract only */ function _withdraw(uint _withdrawAmount) internal returns(bool success) { bool sucsTrPaymnt = _safeTransferPaymnt( beneficiaryFunds, _withdrawAmount); require(sucsTrPaymnt == true); return true; } //_________________________________________________________ /** * @notice Allows to receive coins from Contract Share approved by contract * @notice to receive the share, it has to be already approved by the contract * @notice the share Id will be provided by contract while payments are made through other channels like paypal * @param amountOfCoinsToReceive the allocated allowance of coins to be transferred to you * @param ShrID 1 is FounderShare, 2 is POOLShare, 3 is ColdReserveShare, 4 is VCShare, 5 is PublicShare, 6 is RdmSellPool */ function receiveICOcoins( uint256 amountOfCoinsToReceive, uint ShrID ) public returns (bool success){ msgSndr[msg.sender] = amountOfCoinsToReceive; ICO ico = ICO( _getIcoAddr() ); bool icosuccess; icosuccess = ico.recvShrICO(msg.sender, amountOfCoinsToReceive, ShrID ); require (icosuccess == true); bool sucsTrTk; sucsTrTk = _safeTransferTkn( owner, msg.sender, amountOfCoinsToReceive); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return true; } //_______________________________________________________ // called by other contracts function sendMsgSndr(address caller, address origin) public returns(bool success, uint value){ (success, value) = _sendMsgSndr(caller, origin); return(success, value); } //_______________________________________________________ // function _sendMsgSndr(address caller, address origin) internal returns(bool success, uint value){ require(caller == _getIcoAddr() || caller == _getExchgAddr()); //require(origin == tx.origin); return(true, msgSndr[origin]); } //_______________________________________________________ // function a_viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_){ if(show == true){ Exchg em = Exchg(_getExchgAddr()); ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_) = em.viewSellOffersAtExchangeMacroansy( seller, show) ; return ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_); } } //_________________________________________________________ // function a_viewCoinSupplyAndFunding(bool show) public view returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding){ if(show == true){ ICO ico = ICO( _getIcoAddr() ); ( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding) = ico.getAvlShares(show); return( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding); } } //_______________________________________________________ // /* bool private isEndOk; function endOfRewards(bool isEndNow) public onlyOwner { isEndOk == isEndNow; } function endOfRewardsConfirmed(bool isEndNow) public onlyOwner{ if(isEndOk == true && isEndNow == true) selfdestruct(owner); } */ //_______________________________________________________ } // END_OF_CONTRACT
_________________________________________________________ seller limits check buyer limits check
function _slrByrLmtChk( address seller, uint amountTkns, uint priceOfr, address buyer) internal returns(bool success){ bool successSlrl; (successSlrl) = _chkSellerLmts( seller, amountTkns); bool successByrlAFinl; (successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr); require( successSlrl == true && successByrlAFinl == true); return true; }
7,901,592
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/CLMPriceOracle.sol
token_, the asset to be priced in terms of Canto return price, the price of the asset in terms of canto, in the case of failure, return 0
function getPriceNote(address token_, bool stable) internal view returns(uint) { erc20 token = erc20(token_); address pair; if (stable) { pair = getStablePair(token_); pair = getVolatilePair(note); } } else { uint price; if (pair == address(0)) { return price; } uint decimals = 10 ** token.decimals(); if (IBaseV1Pair(pair).observationLength() < 8) { return 0; } price = IBaseV1Pair(pair).quote(token_, decimals, 8); return price * 1e18 / decimals; }
2,594,950
// SPDX-License-Identifier: GPL-3.0 // Amended by HashLips /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/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/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/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/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/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 ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract HYPECLOUD is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.07 ether; uint256 public maxSupply = 3800; uint256 public maxMintAmount = 3; uint256 public nftPerAddressLimit = 3; bool public paused = false; bool public revealed = false; bool public onlyWhitelisted = true; address[] public whitelistedAddresses; mapping(address => uint256) public addressMintedBalance; 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 { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } require(msg.value >= cost * _mintAmount, "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } 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 setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function withdraw() public payable onlyOwner { // ============================================================================= // This will payout the owner 100% of the contract balance. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } } /** ["0x418Ff54f4982eAeb0Cf7048d02409Cc9309756B0", "0x7816Aa98A2a64Cca08D906422d1bBD54c5e5266E", "0x1F408Bde04080dD6aacD5E5de07dA1dAF527142d"] */
============================================================================= This will payout the owner 100% of the contract balance. Do not remove this otherwise you will not be able to withdraw the funds. ============================================================================= =============================================================================
function withdraw() public payable onlyOwner { require(os); }
295,527
./full_match/80001/0x3c9f40E0C87b96E1B018B29622b4976e349CA19C/sources/contracts/Multisig.sol
Once a function has sufficient approvals, it needs to be signed before executed. transactionId the trx id of trx/ If it reaches the max approvals then automatically exectues the trx
function signTransaction(uint256 transactionId) public { require(transactionId < _transactions.length, "Invalid transaction ID"); Transaction storage transaction = _transactions[transactionId]; require(!transaction.executed, "Transaction already executed"); require(isOwner(msg.sender), "Only owners can sign transactions"); require( !transaction.signatures[msg.sender], "Transaction already signed by this owner" ); transaction.signatures[msg.sender] = true; emit TransactionSigned(transactionId, msg.sender); if (countSignatures(transaction) == _requiredSignatures) { executeTransaction(transactionId); } }
5,651,266
./partial_match/1/0x83C8E4e8b609BDd643b33D6f32fBD6E864fa64a2/sources/ProjectX.sol
Automatically removes tax and limits when renouncing contract. This makes it impossible to raise taxes from 0 just before renounce and bamboozle gamblers./ No need to update max tx / wallet because they are only check when `limited` is true.
function _renounceOwnership() internal override { _buyTax = 2; _saleTax = 4; limited = false; super._renounceOwnership(); }
15,936,316
./full_match/80001/0xd0674b72DEC23984526f9C502EDD91bb8b0317a1/sources/project:/src/contracts/Land.sol
Public View Functions
function getBuildings() public view returns (Building[] memory) { return buildings; }
841,728
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract xCVP is ERC20("", "") { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable cvp; constructor(IERC20 cvp_) public { cvp = cvp_; } /** * @notice Deposits CVP token to receive xCVP * @param _amount CVP amount to deposit * @return shareMinted The minted xCVP amount */ function enter(uint256 _amount) external returns (uint256 shareMinted) { uint256 totalCVP = cvp.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalCVP == 0) { shareMinted = _amount; } else { shareMinted = _amount.mul(totalShares).div(totalCVP); } _mint(msg.sender, shareMinted); cvp.safeTransferFrom(msg.sender, address(this), _amount); } /** * @notice Burn xCVP token to withdraw CVP * @param _share xCVP amount to burn * @return cvpSent The sent CVP amount */ function leave(uint256 _share) external returns (uint256 cvpSent) { uint256 totalShares = totalSupply(); cvpSent = _share.mul(cvp.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); cvp.safeTransfer(msg.sender, cvpSent); } function name() public view override returns (string memory) { return "Staked Concentrated Voting Power"; } function symbol() public view override returns (string memory) { return "xCVP"; } function decimals() public view override returns (uint8) { return uint8(18); } }
Burn xCVP token to withdraw CVP _share xCVP amount to burn return cvpSent The sent CVP amount/
function leave(uint256 _share) external returns (uint256 cvpSent) { uint256 totalShares = totalSupply(); cvpSent = _share.mul(cvp.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); cvp.safeTransfer(msg.sender, cvpSent); }
1,008,658
./full_match/80001/0xDa21C3277F08773b124165632bf5FFd1651fd710/sources/contracts/proxy/ERC1155DaoProxy.sol
returns the fixed price status of the tokens. Signature for isOpenForFixedPrice(uint256,uint256) : `0x0ad0b958` tokenId id of the token. serialNo serial Number of the token. return fixed price status of the tokens./
function isOpenForFixedPrice( uint256 tokenId, uint256 serialNo ) public view returns (bool) { return _erc1155dao.getTokenBearer(tokenId, serialNo).fixedOrAuction == 1; }
9,494,929
./full_match/1/0x8E4Fc8F0d8895Adc6DC20bDc152e0B99364d9B26/sources/contracts/ohdatExchange.sol
TODO add tip. payable(address(owner)).transfer(totalPrice);
function unpause() public { require(hasRole(PAUSER_ROLE, msg.sender)); _unpause(); uint256[] memory mintNftTokenIds; require(_amount > 0,"The purchase amount of NFT must be more than 0!"); require(_amount <= 100,"The purchase amount of NFT must be less than 100!"); require(nftTokenIds.length >= _amount,"The purchase amount of NFT exceeds the stock!"); uint256 totalPrice = _amount.mul(price); require(msg.value >= totalPrice); mintNftTokenIds = _getNftTokenIds(_amount); require(_mintNft(mintNftTokenIds),"NFT mint failed"); payable(address(this)).transfer(totalPrice); if (msg.value > totalPrice){ payable(msg.sender).transfer(msg.value - totalPrice); } _removeNftTokenIds(_amount); emit PurchaseSuccessful(msg.sender,_amount,mintNftTokenIds); }
4,817,648
./full_match/80001/0xfc43C00168D257455be403f2cB206eD0b6A80F4D/sources/contracts/StakingApl.sol
require(addressStaked[_msgSender()] == true, "You are not participated");
function claimReward(uint256 stakeId) external returns (bool){ require(stakeInfos[stakeId].endTS < block.timestamp, "Stake Time is not over yet"); require(stakeInfos[stakeId].claimed == 0, "Already claimed"); uint256 stakeAmount = stakeInfos[stakeId].amount; uint8 rates = stakeInfos[stakeId].rate; uint256 totalTokens = stakeAmount + (stakeAmount * rates); stakeInfos[stakeId].claimed = totalTokens; aplToken.transfer(_msgSender(), totalTokens); emit Claimed(_msgSender(), totalTokens); return true; }
5,619,268
pragma solidity ^0.5.17; import "./Staking/SafeMath96.sol"; import "../openzeppelin/SafeMath.sol"; import "../openzeppelin/SafeERC20.sol"; import "./IFeeSharingProxy.sol"; import "./Staking/IStaking.sol"; contract FeeSharingProxy is SafeMath96, IFeeSharingProxy { using SafeMath for uint256; using SafeERC20 for IERC20; //TODO FEE_WITHDRAWAL_INTERVAL, MAX_CHECKPOINTS uint256 constant FEE_WITHDRAWAL_INTERVAL = 86400; uint32 constant MAX_CHECKPOINTS = 100; IProtocol public protocol; IStaking public staking; /// checkpoints by index per pool token address mapping(address => mapping(uint256 => Checkpoint)) public tokenCheckpoints; /// @notice The number of checkpoints for each pool token address mapping(address => uint32) public numTokenCheckpoints; /// user => token => processed checkpoint mapping(address => mapping(address => uint32)) public processedCheckpoints; //token => time mapping(address => uint256) public lastFeeWithdrawalTime; //token => amount //amount of tokens that were transferred, but were not saved in checkpoints mapping(address => uint96) public unprocessedAmount; struct Checkpoint { uint32 blockNumber; uint32 timestamp; uint96 totalWeightedStake; uint96 numTokens; } /// @notice An event that emitted when fee get withdrawn event FeeWithdrawn(address indexed sender, address indexed token, uint256 amount); /// @notice An event that emitted when tokens transferred event TokensTransferred(address indexed sender, address indexed token, uint256 amount); /// @notice An event that emitted when checkpoint added event CheckpointAdded(address indexed sender, address indexed token, uint256 amount); /// @notice An event that emitted when user fee get withdrawn event UserFeeWithdrawn(address indexed sender, address indexed receiver, address indexed token, uint256 amount); constructor(IProtocol _protocol, IStaking _staking) public { protocol = _protocol; staking = _staking; } /** * @notice withdraw fees for the given token: lendingFee + tradingFee + borrowingFee * @param _token address of the token * */ function withdrawFees(address _token) public { require(_token != address(0), "FeeSharingProxy::withdrawFees: invalid address"); address loanPoolToken = protocol.underlyingToLoanPool(_token); require(loanPoolToken != address(0), "FeeSharingProxy::withdrawFees: loan token not found"); uint256 amount = protocol.withdrawFees(_token, address(this)); require(amount > 0, "FeeSharingProxy::withdrawFees: no tokens to withdraw"); //TODO can be also used - function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn) IERC20(_token).approve(loanPoolToken, amount); uint256 poolTokenAmount = ILoanToken(loanPoolToken).mint(address(this), amount); //update unprocessed amount of tokens uint96 amount96 = safe96(poolTokenAmount, "FeeSharingProxy::withdrawFees: pool token amount exceeds 96 bits"); unprocessedAmount[loanPoolToken] = add96( unprocessedAmount[loanPoolToken], amount96, "FeeSharingProxy::withdrawFees: unprocessedAmount exceeds 96 bits" ); _addCheckpoint(loanPoolToken); emit FeeWithdrawn(msg.sender, loanPoolToken, poolTokenAmount); } /** * @notice transfer tokens to this contract * @dev we just update amount of tokens here and write checkpoint in a separate methods * in order to prevent adding checkpoints too often * @param _token address of the token * @param _amount amount to be transferred * */ function transferTokens(address _token, uint96 _amount) public { require(_token != address(0), "FeeSharingProxy::transferTokens: invalid address"); require(_amount > 0, "FeeSharingProxy::transferTokens: invalid amount"); //transfer tokens from msg.sender bool success = IERC20(_token).transferFrom(address(msg.sender), address(this), _amount); require(success, "Staking::transferTokens: token transfer failed"); //update unprocessed amount of tokens unprocessedAmount[_token] = add96(unprocessedAmount[_token], _amount, "FeeSharingProxy::transferTokens: amount exceeds 96 bits"); _addCheckpoint(_token); emit TokensTransferred(msg.sender, _token, _amount); } /** * @notice adds checkpoint with accumulated amount by function invocation * @param _token address of the token * */ function _addCheckpoint(address _token) internal { if (block.timestamp - lastFeeWithdrawalTime[_token] >= FEE_WITHDRAWAL_INTERVAL) { lastFeeWithdrawalTime[_token] = block.timestamp; uint96 amount = unprocessedAmount[_token]; unprocessedAmount[_token] = 0; //write a regular checkpoint _writeTokenCheckpoint(_token, amount); } } /** * @notice withdraw accumulated fee the message sender * @param _loanPoolToken address of the pool token * @param _maxCheckpoints maximum number of checkpoints to be processed * @param _receiver the receiver of tokens or msg.sender * */ function withdraw( address _loanPoolToken, uint32 _maxCheckpoints, address _receiver ) public { //prevents processing all checkpoints because of block gas limit require(_maxCheckpoints > 0, "FeeSharingProxy::withdraw: _maxCheckpoints should be positive"); address user = msg.sender; if (_receiver == address(0)) { _receiver = msg.sender; } uint256 amount; uint32 end; (amount, end) = _getAccumulatedFees(user, _loanPoolToken, _maxCheckpoints); processedCheckpoints[user][_loanPoolToken] = end; require(IERC20(_loanPoolToken).transfer(user, amount), "FeeSharingProxy::withdraw: withdrawal failed"); emit UserFeeWithdrawn(msg.sender, _receiver, _loanPoolToken, amount); } /** * @notice returns accumulated fee for the message sender * @param _user the address of the user or contract * @param _loanPoolToken address of the pool token * */ function getAccumulatedFees(address _user, address _loanPoolToken) public view returns (uint256) { uint256 amount; (amount, ) = _getAccumulatedFees(_user, _loanPoolToken, 0); return amount; } function _getAccumulatedFees( address _user, address _loanPoolToken, uint32 _maxCheckpoints ) internal view returns (uint256, uint32) { uint32 start = processedCheckpoints[_user][_loanPoolToken]; uint32 end; //additional bool param can't be used because of stack too deep error if (_maxCheckpoints > 0) { //withdraw -> _getAccumulatedFees require(start < numTokenCheckpoints[_loanPoolToken], "FeeSharingProxy::withdrawFees: no tokens for a withdrawal"); end = _getEndOfRange(start, _loanPoolToken, _maxCheckpoints); } else { //getAccumulatedFees -> _getAccumulatedFees //don't throw error for getter invocation outside of transaction if (start >= numTokenCheckpoints[_loanPoolToken]) { return (0, numTokenCheckpoints[_loanPoolToken]); } end = numTokenCheckpoints[_loanPoolToken]; } uint256 amount = 0; uint256 cachedLockDate = 0; uint96 cachedWeightedStake = 0; for (uint32 i = start; i < end; i++) { Checkpoint storage checkpoint = tokenCheckpoints[_loanPoolToken][i]; uint256 lockDate = staking.timestampToLockDate(checkpoint.timestamp); uint96 weightedStake; if (lockDate == cachedLockDate) { weightedStake = cachedWeightedStake; } else { //We need to use "checkpoint.blockNumber - 1" here to calculate weighted stake //for the same block like we did for total voting power in _writeTokenCheckpoint weightedStake = staking.getPriorWeightedStake(_user, checkpoint.blockNumber - 1, checkpoint.timestamp); cachedWeightedStake = weightedStake; cachedLockDate = lockDate; } uint256 share = uint256(checkpoint.numTokens).mul(weightedStake).div(uint256(checkpoint.totalWeightedStake)); amount = amount.add(share); } return (amount, end); } function _getEndOfRange( uint32 start, address _loanPoolToken, uint32 _maxCheckpoints ) internal view returns (uint32) { uint32 nCheckpoints = numTokenCheckpoints[_loanPoolToken]; uint32 end; if (_maxCheckpoints == 0) { //all checkpoints will be processed (only for getter outside of a transaction) end = nCheckpoints; } else { if (_maxCheckpoints > MAX_CHECKPOINTS) { _maxCheckpoints = MAX_CHECKPOINTS; } end = safe32(start + _maxCheckpoints, "FeeSharingProxy::withdraw: checkpoint index exceeds 32 bits"); if (end > nCheckpoints) { end = nCheckpoints; } } //Withdrawal should only be possible for blocks which were already mined. uint32 lastBlockNumber = tokenCheckpoints[_loanPoolToken][end - 1].blockNumber; if (block.number == lastBlockNumber) { end--; } return end; } function _writeTokenCheckpoint(address _token, uint96 _numTokens) internal { uint32 blockNumber = safe32(block.number, "FeeSharingProxy::_writeCheckpoint: block number exceeds 32 bits"); uint32 blockTimestamp = safe32(block.timestamp, "FeeSharingProxy::_writeCheckpoint: block timestamp exceeds 32 bits"); uint32 nCheckpoints = numTokenCheckpoints[_token]; uint96 totalWeightedStake = staking.getPriorTotalVotingPower(blockNumber - 1, block.timestamp); if (nCheckpoints > 0 && tokenCheckpoints[_token][nCheckpoints - 1].blockNumber == blockNumber) { tokenCheckpoints[_token][nCheckpoints - 1].totalWeightedStake = totalWeightedStake; tokenCheckpoints[_token][nCheckpoints - 1].numTokens = _numTokens; } else { tokenCheckpoints[_token][nCheckpoints] = Checkpoint(blockNumber, blockTimestamp, totalWeightedStake, _numTokens); numTokenCheckpoints[_token] = nCheckpoints + 1; } emit CheckpointAdded(msg.sender, _token, _numTokens); } } interface IProtocol { function withdrawFees(address token, address receiver) external returns (uint256); function underlyingToLoanPool(address token) external returns (address); } interface ILoanToken { function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount); }
withdraw accumulated fee the message sender _loanPoolToken address of the pool token _maxCheckpoints maximum number of checkpoints to be processed _receiver the receiver of tokens or msg.sender /prevents processing all checkpoints because of block gas limit
function withdraw( address _loanPoolToken, uint32 _maxCheckpoints, address _receiver ) public { require(_maxCheckpoints > 0, "FeeSharingProxy::withdraw: _maxCheckpoints should be positive"); address user = msg.sender; if (_receiver == address(0)) { _receiver = msg.sender; } uint256 amount; uint32 end; (amount, end) = _getAccumulatedFees(user, _loanPoolToken, _maxCheckpoints); processedCheckpoints[user][_loanPoolToken] = end; require(IERC20(_loanPoolToken).transfer(user, amount), "FeeSharingProxy::withdraw: withdrawal failed"); emit UserFeeWithdrawn(msg.sender, _receiver, _loanPoolToken, amount); }
7,285,472
./full_match/1/0x635C30A7A4C7F354Bd8ec3F6B1a79424F6040Dc7/sources/Napkin.sol
Enable or disable internal swaps Set "true" to enable internal swaps for trreasury
function setSwapEnabled(bool _enabled) external onlyOwner { swapEnabled = _enabled; }
8,345,507
./partial_match/1/0x11B23B2c7CcDf916B489323B814AdD16f82e510D/sources/PlanetStakingPool.sol
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), "OwnershipManager: new owner is the zero address" ); _transferOwnership(newOwner); }
4,400,380
./full_match/1/0xC0eaA22Fdff044F38B79624D65F4eB68c7238703/sources/scripts/Campaign.sol
Initialize a new campaign. - Access control: External. Can only be called by the factory contract./
function initialize ( address _token, address _campaignOwner, uint256[4] calldata _stats, uint256[4] calldata _dates, uint256[3] calldata _liquidity, bool _burnUnSold, uint256 _tokenLockTime, uint256[6] calldata _tierWeights, uint256[6] calldata _tierMinTokens ) external { require(msg.sender == factory,'Only factory allowed to initialize'); token = _token; campaignOwner = _campaignOwner; softCap = _stats[0]; hardCap = _stats[1]; tokenSalesQty = _stats[2]; feePcnt = _stats[3]; startDate = _dates[0]; endDate = _dates[1]; regEndDate = _dates[2]; tierSaleEndDate = _dates[3]; lpMATICQty = _liquidity[0]; lpTokenQty = _liquidity[1]; lpLockDuration = _liquidity[2]; burnUnSold = _burnUnSold; tokenLockTime = _tokenLockTime; for(uint256 i=0; i<_tierWeights.length; i++) { indexToTier[i+1] = TierProfile(_tierWeights[i], _tierMinTokens[i], 0); } }
3,183,377
./partial_match/1/0x1c288F6efc68b984D7A26Aba3Cdfd0C144517C70/sources/PEPEPUTIN.sol
OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, 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 from, address to, uint256 amount ) external returns (bool); pragma solidity ^0.8.0; }
4,380,316
./full_match/4/0x3ca5b514BEba80F20ebaf37293f442537bD7B5E1/sources/Benz/Bugatti.sol
SPDX-License-Identifier: Unlicensed
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); #Bolon }
721,380
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/src/interfaces/IERC1155.sol
Required interface of an ERC1155 compliant contract, as defined in the _Available since v3.1._/
interface IERC1155 is IERC165 { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); event URI(string value, uint256 indexed id); function balanceOf( address account, uint256 id ) external view returns (uint256); function balanceOfBatch( address[] calldata accounts, uint256[] calldata ids ) external view returns (uint256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll( address account, address operator ) external view returns (bool); function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; import {IERC165} from "core/interfaces/IERC165.sol"; }
8,451,474
pragma solidity ^0.4.24; import "../math/SafeMath.sol"; /** * @title SplitPayment * @dev This contract can be used when payments need to be received by a group * of people and split proportionately to some number of shares they own. */ contract SplitPayment { using SafeMath for uint256; uint256 private totalShares_ = 0; uint256 private totalReleased_ = 0; mapping(address => uint256) private shares_; mapping(address => uint256) private released_; address[] private payees_; /** * @dev Constructor */ constructor(address[] _payees, uint256[] _shares) public payable { require(_payees.length == _shares.length); require(_payees.length > 0); for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** * @dev payable fallback */ function () external payable {} /** * @return the total shares of the contract. */ function totalShares() public view returns(uint256) { return totalShares_; } /** * @return the total amount already released. */ function totalReleased() public view returns(uint256) { return totalReleased_; } /** * @return the shares of an account. */ function shares(address _account) public view returns(uint256) { return shares_[_account]; } /** * @return the amount already released to an account. */ function released(address _account) public view returns(uint256) { return released_[_account]; } /** * @return the address of a payee. */ function payee(uint256 index) public view returns(address) { return payees_[index]; } /** * @dev Release one of the payee's proportional payment. * @param _payee Whose payments will be released. */ function release(address _payee) public { require(shares_[_payee] > 0); uint256 totalReceived = address(this).balance.add(totalReleased_); uint256 payment = totalReceived.mul( shares_[_payee]).div( totalShares_).sub( released_[_payee] ); require(payment != 0); assert(address(this).balance >= payment); released_[_payee] = released_[_payee].add(payment); totalReleased_ = totalReleased_.add(payment); _payee.transfer(payment); } /** * @dev Add a new payee to the contract. * @param _payee The address of the payee to add. * @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0)); require(_shares > 0); require(shares_[_payee] == 0); payees_.push(_payee); shares_[_payee] = _shares; totalShares_ = totalShares_.add(_shares); } }
Release one of the payee's proportional payment. _payee Whose payments will be released./
function release(address _payee) public { require(shares_[_payee] > 0); uint256 totalReceived = address(this).balance.add(totalReleased_); uint256 payment = totalReceived.mul( shares_[_payee]).div( totalShares_).sub( released_[_payee] ); require(payment != 0); assert(address(this).balance >= payment); released_[_payee] = released_[_payee].add(payment); totalReleased_ = totalReleased_.add(payment); _payee.transfer(payment); }
13,046,277
pragma solidity ^0.5.8; // Importing OpenZeppelin's SafeMath Implementation import 'https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol'; contract TheCrowdChain { using SafeMath for uint256; Cause[] private causes; event CauseCreated( address causeAddress, address creator, string title, string cause_type, string desciption, uint256 goal ); /* Function to create a new cause */ function startCause(string calldata title, string calldata cause_type, string calldata description, uint goal) external{ //creating an object for cause contract Cause newCauses = new Cause(msg.sender, title, cause_type, description, goal); //push in causes array created earlier causes.push(newCauses); //emit CauseCreated event emit CauseCreated( address(newCauses), msg.sender, title, cause_type, description, goal ); } /* Function to list all the causes */ function getAllCauses() external view returns(Cause[] memory ) { return causes; } } contract Cause{ using SafeMath for uint256; //charity cause current status enum State { pending, completed } address payable public creator; uint public goal; uint256 public current; string public title; string public cause_type; string public description; State public state = State.pending; mapping(address => uint) public donors; //event when ever funding or donation is received event donationReceived(address donor, uint amount, uint current); //event when donation is completed and amount is dispatched event donationSentToTarget(address recipient); //check the current state via modifier modifier checkState(State state_){ require(state == state_); _; } //check if caller is creator modifier isCreator(){ require(msg.sender == creator); _; } constructor( address payable c_starter, string memory c_title, string memory c_type, string memory c_description, uint c_goal ) public { creator = c_starter; title = c_title; cause_type = c_type; description = c_description; goal = c_goal; current = 0; } /* Function to contribute/donate to cause*/ function donate() external checkState(State.pending) payable{ require(msg.sender != creator); donors[msg.sender] = donors[msg.sender].add(msg.value); current = current.add(msg.value); //emit donationReceived event emit donationReceived(msg.sender, msg.value, current); //check if donation is completed checkIfDonationCompleted(); } function checkIfDonationCompleted() public { if(current >= goal){ state = State.completed; payToTarget(); } } function payToTarget() internal checkState(State.completed) returns (bool) { uint256 raised = current; current = 0; if(creator.send(raised)){ emit donationSentToTarget(creator); return true; } else{ current = raised; state = State.completed; } return false; } function get() public view returns ( address payable c_starter, string memory c_title, string memory c_type, string memory c_description, State currentState, uint256 c_goal, uint256 c_raised ) { c_starter = creator; c_title = title; c_type = cause_type; currentState = state; c_description = description; c_goal = goal; c_raised = current; } }
Function to create a new cause /creating an object for cause contractpush in causes array created earlieremit CauseCreated event
function startCause(string calldata title, string calldata cause_type, string calldata description, uint goal) external{ Cause newCauses = new Cause(msg.sender, title, cause_type, description, goal); causes.push(newCauses); emit CauseCreated( address(newCauses), msg.sender, title, cause_type, description, goal ); }
6,416,015
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.0; import "@cartesi/pos/contracts/IWorkerManagerAuthManager.sol"; import "./interfaces/StakingPoolWorker.sol"; import "./StakingPoolData.sol"; contract StakingPoolWorkerImpl is StakingPoolWorker, StakingPoolData { IWorkerManagerAuthManager immutable workerManager; // all immutable variables can stay at the constructor constructor(address _workerManager) { require( _workerManager != address(0), "parameter can not be zero address" ); workerManager = IWorkerManagerAuthManager(_workerManager); } receive() external payable {} function __StakingPoolWorkerImpl_update(address _pos) internal { workerManager.authorize(address(this), _pos); pos = IPoS(_pos); } /// @notice allows for the pool to act on its own behalf when producing blocks. function selfhire() external payable override { // pool needs to be both user and worker workerManager.hire{value: msg.value}(payable(address(this))); workerManager.authorize(address(this), address(pos)); workerManager.acceptJob(); payable(msg.sender).transfer(msg.value); } /// @notice Asks the worker to work for the sender. Sender needs to pay something. /// @param workerAddress address of the worker function hire(address payable workerAddress) external payable override onlyOwner { workerManager.hire{value: msg.value}(workerAddress); workerManager.authorize(workerAddress, address(pos)); } /// @notice Called by the user to cancel a job offer /// @param workerAddress address of the worker node function cancelHire(address workerAddress) external override onlyOwner { workerManager.cancelHire(workerAddress); } /// @notice Called by the user to retire his worker. /// @param workerAddress address of the worker to be retired /// @dev this also removes all authorizations in place function retire(address payable workerAddress) external override onlyOwner { workerManager.retire(workerAddress); } }
allows for the pool to act on its own behalf when producing blocks. pool needs to be both user and worker
function selfhire() external payable override { workerManager.authorize(address(this), address(pos)); workerManager.acceptJob(); payable(msg.sender).transfer(msg.value); }
2,576,919
pragma solidity ^0.5.7; // ------------------------------------------------------------------------ // Math library // ------------------------------------------------------------------------ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256){ uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ------------------------------------------------------------------------ // Ownable contract definition // This is to allow for admin specific functions // ------------------------------------------------------------------------ contract Ownable { address payable public owner; address payable public potentialNewOwner; event OwnershipTransferred(address payable indexed _from, address payable indexed _to); // ------------------------------------------------------------------------ // Upon creation we set the creator as the owner // ------------------------------------------------------------------------ constructor() public { owner = msg.sender; } // ------------------------------------------------------------------------ // Set up the modifier to only allow the owner to pass through the condition // ------------------------------------------------------------------------ modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Transfer ownership to another user // ------------------------------------------------------------------------ function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; } // ------------------------------------------------------------------------ // To ensure correct transfer, the new owner has to confirm new ownership // ------------------------------------------------------------------------ function acceptOwnership() public { require(msg.sender == potentialNewOwner); emit OwnershipTransferred(owner, potentialNewOwner); owner = potentialNewOwner; } } // ------------------------------------------------------------------------ // Content moderatable contract definition // This is to allow for moderator specific functions // ------------------------------------------------------------------------ contract Moderatable is Ownable{ mapping(address => bool) public moderators; event ModeratorAdded(address indexed _moderator); event ModeratorRemoved(address indexed _moderator); // ------------------------------------------------------------------------ // Upon creation we set the first moderator as the owner // ------------------------------------------------------------------------ constructor() public { addModerator(owner); } // ------------------------------------------------------------------------ // Set up the modifier to only allow moderators to pass through the condition // ------------------------------------------------------------------------ modifier onlyModerators() { require(moderators[msg.sender] == true); _; } // ------------------------------------------------------------------------ // Add a moderator // ------------------------------------------------------------------------ function addModerator(address _newModerator) public onlyOwner { moderators[_newModerator] = true; emit ModeratorAdded(_newModerator); } // ------------------------------------------------------------------------ // Remove a moderator // ------------------------------------------------------------------------ function removeModerator(address _moderator) public onlyOwner { moderators[_moderator] = false; emit ModeratorRemoved(_moderator); } } // ------------------------------------------------------------------------ // Storage token definition // ------------------------------------------------------------------------ contract MoralityContentStorage is Moderatable{ using SafeMath for uint256; struct ContentMap{ uint256[] contentIds; mapping(uint256 => bool) containsContentId; bool exists; } uint256[] internal uniqueContentIds; uint256[] internal uniqueArticleIds; uint256[] internal uniqueSubArticleIds; mapping(uint256 => bool) internal contentIdExists; mapping(uint256 => ContentMap) internal articleContentIds; mapping(uint256 => ContentMap) internal subArticleContentIds; mapping(uint256 => string) internal contentById; uint256 public perPage = 6; event ContentAdded(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp); event ContentAddedViaEvent(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp, string data); // ------------------------------------------------------------------------ // Add content to event for content persistance - cheap // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { emit ContentAddedViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content for content persistance expensive - expensive // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { //Add contentId to list of already added contents _addUniqueIdToContentsList(contentId); //Add the data _addContent(contentId, data); //Add to the unique article list _addUniqueIdToArticleList(articleId); //Add to the unique article list _addUniqueIdToSubArticleList(subArticleId); //Map the articleId to the contentId _addArticleToContentMap(articleId, contentId); //Map the subArticleId to the contentId _addSubArticleToContentMap(subArticleId, contentId); //Add event (everything but content) emit ContentAdded(contentCreator, articleId, subArticleId, contentId, timestamp); } // ------------------------------------------------------------------------ // Get Content by contentId // ------------------------------------------------------------------------ function getContentById(uint256 contentId) public view returns(string memory) { return contentById[contentId]; } // ------------------------------------------------------------------------ // Get all content ids // ------------------------------------------------------------------------ function getAllContentIds() public view returns(uint256[] memory) { return uniqueContentIds; } // ------------------------------------------------------------------------ // Get all article ids // ------------------------------------------------------------------------ function getAllArticleIds() public view returns(uint256[] memory) { return uniqueArticleIds; } // ------------------------------------------------------------------------ // Get all sub-article ids // ------------------------------------------------------------------------ function getAllSubArticleIds() public view returns(uint256[] memory) { return uniqueSubArticleIds; } // ------------------------------------------------------------------------ // Get all content count // ------------------------------------------------------------------------ function getAllContentCount() public view returns(uint256) { return uniqueContentIds.length; } // ------------------------------------------------------------------------ // Get all content ids for article // ------------------------------------------------------------------------ function getAllContentIdsForArticle(uint256 articleId) public view returns(uint256[] memory) { return articleContentIds[articleId].contentIds; } // ------------------------------------------------------------------------ // Count content for article // ------------------------------------------------------------------------ function countContentForArticle(uint256 articleId) public view returns(uint256) { return articleContentIds[articleId].contentIds.length; } // ------------------------------------------------------------------------ // Get all content ids for sub-article // ------------------------------------------------------------------------ function getAllContentIdsForSubArticle(uint256 subArticleId) public view returns(uint256[] memory) { return subArticleContentIds[subArticleId].contentIds; } // ------------------------------------------------------------------------ // Count content for sub-article // ------------------------------------------------------------------------ function countContentForSubArticle(uint256 subArticleId) public view returns(uint256) { return subArticleContentIds[subArticleId].contentIds.length; } // ------------------------------------------------------------------------ // Get page for sub article (page starts at 0) ~ all to avoid experimental // ------------------------------------------------------------------------ function getPageForSubArticle(uint256 subArticleId, uint256 page) public view returns(string memory,string memory,string memory,string memory,string memory,string memory) { //Set up the page string[] memory contentToReturn = new string[](perPage); //Get all content ids for sub-article uint256[] memory contentIds = getAllContentIdsForSubArticle(subArticleId); //Get minimum index based on page uint256 indexMin = _getMinimumIndex(page); //Add the content ids to the page for(uint256 i=0; i<perPage;i++){ //Get current index based on page uint256 currentIndex = _getCurrentIndex(indexMin, i); //If the current index exists then add the content to the page if(contentIds.length > currentIndex){ uint256 id = contentIds[currentIndex]; contentToReturn[i] = getContentById(id); } } //Return the page return _returnPageOfContent(contentToReturn[0], contentToReturn[1], contentToReturn[2], contentToReturn[3], contentToReturn[4], contentToReturn[5]); } // ------------------------------------------------------------------------ // Get page for article (page starts at 0) ~ all to avoid experimental // To break this method down, we need to use the experimental encoder // ------------------------------------------------------------------------ function getPageForArticle(uint256 articleId, uint256 page) public view returns(string memory,string memory,string memory,string memory,string memory,string memory) { //Set up the page string[] memory contentToReturn = new string[](perPage); //Get all content ids for article uint256[] memory contentIds = getAllContentIdsForArticle(articleId); //Get minimum index based on page uint256 indexMin = _getMinimumIndex(page); //Add the content ids to the page for(uint256 i=0; i<perPage;i++){ //Get current index based on page uint256 currentIndex = _getCurrentIndex(indexMin, i); //If the current index exists then add the content to the page if(contentIds.length > currentIndex){ uint256 id = contentIds[currentIndex]; contentToReturn[i] = getContentById(id); } } //Return the page return _returnPageOfContent(contentToReturn[0], contentToReturn[1], contentToReturn[2], contentToReturn[3], contentToReturn[4], contentToReturn[5]); } //Internal helpers--------------------------------------------------------- // ------------------------------------------------------------------------ // Add unique article Id to array // ------------------------------------------------------------------------ function _addUniqueIdToArticleList(uint256 articleId) internal{ if(articleContentIds[articleId].exists == false) { uniqueArticleIds.push(articleId); } } // ------------------------------------------------------------------------ // Add unique sub-article Id to array // ------------------------------------------------------------------------ function _addUniqueIdToSubArticleList(uint256 subArticleId) internal{ if(subArticleContentIds[subArticleId].exists == false) { uniqueSubArticleIds.push(subArticleId); } } // ------------------------------------------------------------------------ // Add unique article Id to array // ------------------------------------------------------------------------ function _addArticleToContentMap(uint256 articleId, uint256 contentId) internal{ if(articleContentIds[articleId].containsContentId[contentId] == false){ articleContentIds[articleId].exists = true; articleContentIds[articleId].contentIds.push(contentId); articleContentIds[articleId].containsContentId[contentId] = true; } } // ------------------------------------------------------------------------ // Add unique sub-article Id to array // ------------------------------------------------------------------------ function _addSubArticleToContentMap(uint256 subArticleId, uint256 contentId) internal{ if(subArticleContentIds[subArticleId].containsContentId[contentId] == false){ subArticleContentIds[subArticleId].exists = true; subArticleContentIds[subArticleId].contentIds.push(contentId); subArticleContentIds[subArticleId].containsContentId[contentId] = true; } } // ------------------------------------------------------------------------ // Add unique content Id to array // ------------------------------------------------------------------------ function _addUniqueIdToContentsList(uint256 contentId) internal{ if(contentIdExists[contentId] == false){ uniqueContentIds.push(contentId); contentIdExists[contentId] = true; } } // ------------------------------------------------------------------------ // Try to add content if it doesnt exist // ------------------------------------------------------------------------ function _addContent(uint256 contentId, string memory data) internal{ contentById[contentId] = data; } // ------------------------------------------------------------------------ // Get minimum index based on page // ------------------------------------------------------------------------ function _getMinimumIndex(uint256 page) internal view returns(uint256){ return page.mul(perPage.sub(1)); } // ------------------------------------------------------------------------ // Get current index from base of index min plus the loop index // ------------------------------------------------------------------------ function _getCurrentIndex(uint256 indexMin, uint256 loopIndex) internal pure returns(uint256){ return indexMin.add(loopIndex); } // ------------------------------------------------------------------------ // This mapping saves a block of code written out twice // ------------------------------------------------------------------------ function _returnPageOfContent(string memory pageItem1, string memory pageItem2, string memory pageItem3, string memory pageItem4, string memory pageItem5, string memory pageItem6) internal pure returns(string memory,string memory,string memory,string memory,string memory,string memory) { return(pageItem1, pageItem2, pageItem3, pageItem4, pageItem5, pageItem6); } }
------------------------------------------------------------------------ This mapping saves a block of code written out twice ------------------------------------------------------------------------
function _returnPageOfContent(string memory pageItem1, string memory pageItem2, string memory pageItem3, string memory pageItem4, string memory pageItem5, string memory pageItem6) internal pure returns(string memory,string memory,string memory,string memory,string memory,string memory) { return(pageItem1, pageItem2, pageItem3, pageItem4, pageItem5, pageItem6); }
6,403,621
./full_match/1/0xaBcf18BF1937e3d7Bac7Ac743b7829aD6aD6D2ca/sources/contracts/helpers/OwnableUpgradeable.sol
Initializes the contract setting the deployer as the initial owner./
function __Ownable_init(address _ownerOnInit) internal onlyInitializing { __Ownable_init_unchained(_ownerOnInit); }
17,053,634
./full_match/44787/0x08822Da015207E89647c4F0B5C0132c61f2C7733/sources/project_/contracts/UnergyLogicOperation.sol
Scaled value by 1e6;
function invoiceReport( address _projectAddr, uint256 income, uint256 _energyDelta, uint256 _energyTariff, uint256 _depreciationPercentage ) internal { DataStructure.Project memory project = unergyData.getProject(_projectAddr); DataStructure.DepreciatedBalance memory depreciatedBalance = unergyData.getDepreciatedBalance(); DataStructure.Tokens memory tokens = project.tokens; uint256 totalSupply = tokens.pWatts; DataStructure.ProjectState state = project.state; uint256 eventDepreciation; if (state == DataStructure.ProjectState.INSTALLED) { eventDepreciation = 0; uint256 pWattDepreciated = Math.mulDiv( totalSupply, _depreciationPercentage, 1e8 ); depreciatedBalance.pWattDepreciated += pWattDepreciated; project.pWattDepreciated += pWattDepreciated; ERC20Abs pWatt = ERC20Abs(_projectAddr); pWatt.burn( address(this), pWattDepreciated ); eventDepreciation = project.pWattDepreciated; unergyData.updateProject( _projectAddr, project ); unergyData.setDepreciatedBalance(depreciatedBalance); ERC1155Abs cleanEnergyAssets = ERC1155Abs(cleanEnergyAssetsAddr); cleanEnergyAssets.burn( _projectAddr, _energyDelta ); emit InvoiceReport( _projectAddr, _energyDelta, _energyTariff, income, eventDepreciation ); }
13,270,996
pragma solidity ^0.4.23; import "../IDaoBase.sol"; import "./IProposal.sol"; import "../utils/UtilsLib.sol"; import "../tokens/StdDaoToken.sol"; library VotingLib { event Voted(address _who, bool _yes); event CallAction(); event DelegatedTo(address _sender, uint _tokensAmount); event DelegationRemoved(address _from, address _to); enum VotingType{ NoVoting, Voting1p1v, VotingSimpleToken, VotingQuadratic, VotingLiquid } struct Delegation { address _address; uint amount; bool isDelegator; // is it account who delegates the tokens } struct Vote { address voter; bool isYes; } struct VotingStorage { IDaoBase daoBase; IProposal proposal; address votingCreator; uint minutesToVote; bool finishedWithYes; bool canceled; uint genesis; uint quorumPercent; uint consensusPercent; address tokenAddress; uint votingID; string groupName; mapping(address=>bool) voted; mapping(uint=>Vote) votes; mapping(address=>Delegation[]) delegations; uint votesCount; VotingType votingType; } function generalConstructor( VotingStorage storage store, IDaoBase _daoBase, IProposal _proposal, address _origin, VotingType _votingType, uint _minutesToVote, string _groupName, uint _quorumPercent, uint _consensusPercent, address _tokenAddress) public { require((_quorumPercent<=100)&&(_quorumPercent>0)); require((_consensusPercent<=100)&&(_consensusPercent>0)); store.votingCreator = _origin; store.daoBase = _daoBase; store.proposal = _proposal; store.minutesToVote = _minutesToVote; store.quorumPercent = _quorumPercent; store.consensusPercent = _consensusPercent; store.groupName = _groupName; store.votingType = _votingType; store.genesis = block.timestamp; if(VotingType.Voting1p1v!=store.votingType) { store.tokenAddress = _tokenAddress; store.votingID = StdDaoToken(_tokenAddress).startNewVoting(); } // This is now commented here. DO NOT UNCOMMENT. // Please manually call the 'voteFromOriginPositive' // right after Voting is created! // //libVote(store, _origin, true); } /** * @param store storage instance address * @return number of total voters */ function getVotersTotal(VotingStorage storage store)public view returns(uint) { if(VotingType.Voting1p1v==store.votingType) { return store.daoBase.getMembersCount(store.groupName); }else if(VotingType.VotingSimpleToken==store.votingType) { return StdDaoToken(store.tokenAddress).totalSupply(); }else if(VotingType.VotingQuadratic==store.votingType) { return StdDaoToken(store.tokenAddress).getVotingTotalForQuadraticVoting(); }else if(VotingType.VotingLiquid==store.votingType) { return StdDaoToken(store.tokenAddress).totalSupply(); }else { revert(); } } /** * @param store storage instance address * @param _voter address of voter * @return power of voter */ function getPowerOf(VotingStorage storage store, address _voter)public view returns(uint) { if(VotingType.Voting1p1v==store.votingType) { if(store.daoBase.isGroupMember(store.groupName, _voter)) { return 1; }else { return 0; } }else if(VotingType.VotingSimpleToken==store.votingType) { return StdDaoToken(store.tokenAddress).getBalanceAtVoting(store.votingID, _voter); }else if(VotingType.VotingQuadratic==store.votingType) { return UtilsLib.sqrt(StdDaoToken(store.tokenAddress).getBalanceAtVoting(store.votingID, _voter)); }else if(VotingType.VotingLiquid==store.votingType) { uint res = StdDaoToken(store.tokenAddress).getBalanceAtVoting(store.votingID, _voter); for(uint i = 0; i < store.delegations[_voter].length; i++) { if(!store.delegations[_voter][i].isDelegator) { res += store.delegations[_voter][i].amount; }else { res -= store.delegations[_voter][i].amount; } } return res; }else { revert(); } } /** * @param store storage instance address * @param _voter voter * @param _isYes vote * @dev vote function */ function libVote(VotingStorage storage store, address _voter, bool _isYes) public { require(!isFinished(store)); require(!store.voted[msg.sender]); if(VotingType.Voting1p1v==store.votingType) { require(store.daoBase.isGroupMember(store.groupName, _voter)); } store.votes[store.votesCount] = Vote(_voter, _isYes); store.voted[_voter] = true; store.votesCount += 1; emit Voted(msg.sender, _isYes); callActionIfEnded(store); } /** * @param store storage instance address * @return true if voting finished */ function isFinished(VotingStorage storage store) public view returns(bool) { if(store.canceled||store.finishedWithYes) { return true; }else if(store.minutesToVote>0) { return _isTimeElapsed(store); }else { return _isQuorumReached(store); } } /** * @param store storage instance address * @return true if time creation + minutes to vote < now */ function _isTimeElapsed(VotingStorage storage store) internal view returns(bool) { if(store.minutesToVote==0) { return false; } return (block.timestamp - store.genesis) > (store.minutesToVote * 60 * 1000); } /** * @param store storage instance address * @return true if voters total * quorum percent <= all votes * 100 */ function _isQuorumReached(VotingStorage storage store) internal view returns(bool) { var (yesResults, noResults, votersTotal) = getVotingStats(store); return ((yesResults + noResults) * 100) >= (votersTotal * store.quorumPercent); } /** * @param store storage instance address * @return true if all votes * consensus percent <= yes votes * 100 */ function _isConsensusReached(VotingStorage storage store) internal view returns(bool) { var (yesResults, noResults, votersTotal) = getVotingStats(store); return (yesResults * 100) >= ((yesResults + noResults) * store.consensusPercent); } /** * @param store storage instance address * @return true if voting finished with yes */ function isYes(VotingStorage storage store) public view returns(bool) { if(true==store.finishedWithYes) { return true; } return !store.canceled&& isFinished(store)&& _isQuorumReached(store)&& _isConsensusReached(store); } /** * @param store storage instance address * @return amount of yes, no and voters total */ function getVotingStats(VotingStorage storage store) public view returns(uint yesResults, uint noResults, uint votersTotal) { for(uint i=0; i<store.votesCount; ++i) { if(store.votes[i].isYes) { yesResults+= getPowerOf(store, store.votes[i].voter); }else { noResults+= getPowerOf(store, store.votes[i].voter); } } votersTotal = getVotersTotal(store); return; } /** * @param store storage instance address * @param _of address * @return delegated power for account _of */ function getDelegatedPowerOf(VotingStorage storage store, address _of) public view returns(uint res) { for(uint i = 0; i < store.delegations[_of].length; i++) { if(!store.delegations[_of][i].isDelegator) { res += store.delegations[_of][i].amount; } } } /** * @param store storage instance address * @param _to address * @return delegated power to account _to by msg.sender */ function getDelegatedPowerByMe(VotingStorage storage store, address _to) public view returns(uint res) { for(uint i = 0; i < store.delegations[msg.sender].length; i++) { if(store.delegations[msg.sender][i]._address == _to) { if(store.delegations[msg.sender][i].isDelegator) { res += store.delegations[msg.sender][i].amount; } } } } /** * @param store storage instance address * @param _to address * @param _tokenAmount amount of tokens which will be delegated * @dev delegate power to account _to by msg.sender */ function delegateMyVoiceTo(VotingStorage storage store, address _to, uint _tokenAmount) public { require (_to!= address(0)); require (_tokenAmount <= StdDaoToken(store.tokenAddress).getBalanceAtVoting(store.votingID, msg.sender)); for(uint i = 0; i < store.delegations[_to].length; i++) { if(store.delegations[_to][i]._address == msg.sender) { store.delegations[_to][i].amount = _tokenAmount; } } for(i = 0; i < store.delegations[msg.sender].length; i++) { if(store.delegations[msg.sender][i]._address == _to) { store.delegations[msg.sender][i].amount = _tokenAmount; emit DelegatedTo(_to, _tokenAmount); return; } } store.delegations[_to].push(Delegation(msg.sender, _tokenAmount, false)); store.delegations[msg.sender].push(Delegation(_to, _tokenAmount, true)); } /** * @param store storage instance address * @param _to address * @dev remove delegation for account _to */ function removeDelegation(VotingStorage storage store, address _to) public { require (_to!= address(0)); for(uint i = 0; i < store.delegations[_to].length; i++) { if(store.delegations[_to][i]._address == msg.sender) { store.delegations[_to][i].amount = 0; } } for(i = 0; i < store.delegations[msg.sender].length; i++) { if(store.delegations[msg.sender][i]._address == _to) { store.delegations[msg.sender][i].amount = 0; } } emit DelegationRemoved(msg.sender, _to); } /** * @param store storage instance address * @dev call action when voting finished with yes */ function callActionIfEnded(VotingStorage storage store) public { if(!store.finishedWithYes && isFinished(store) && isYes(store)) { // should not be callable again!!! store.finishedWithYes = true; emit CallAction(); store.proposal.action(); // can throw! } } }
store storage instance address _voter voter _isYes vote vote function/
function libVote(VotingStorage storage store, address _voter, bool _isYes) public { require(!isFinished(store)); require(!store.voted[msg.sender]); if(VotingType.Voting1p1v==store.votingType) { require(store.daoBase.isGroupMember(store.groupName, _voter)); } store.votes[store.votesCount] = Vote(_voter, _isYes); store.voted[_voter] = true; store.votesCount += 1; emit Voted(msg.sender, _isYes); callActionIfEnded(store); }
7,264,734
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /// @title Role based access control mixin for Rasmart Platform /// @author Abha Mai <[email protected]> /// @dev Ignore DRY approach to achieve readability contract RBACMixin { /// @notice Constant string message to throw on lack of access string constant FORBIDDEN = "Haven't enough right to access"; /// @notice Public map of owners mapping (address => bool) public owners; /// @notice Public map of minters mapping (address => bool) public minters; /// @notice The event indicates the addition of a new owner /// @param who is address of added owner event AddOwner(address indexed who); /// @notice The event indicates the deletion of an owner /// @param who is address of deleted owner event DeleteOwner(address indexed who); /// @notice The event indicates the addition of a new minter /// @param who is address of added minter event AddMinter(address indexed who); /// @notice The event indicates the deletion of a minter /// @param who is address of deleted minter event DeleteMinter(address indexed who); constructor () public { _setOwner(msg.sender, true); } /// @notice The functional modifier rejects the interaction of senders who are not owners modifier onlyOwner() { require(isOwner(msg.sender), FORBIDDEN); _; } /// @notice Functional modifier for rejecting the interaction of senders that are not minters modifier onlyMinter() { require(isMinter(msg.sender), FORBIDDEN); _; } /// @notice Look up for the owner role on providen address /// @param _who is address to look up /// @return A boolean of owner role function isOwner(address _who) public view returns (bool) { return owners[_who]; } /// @notice Look up for the minter role on providen address /// @param _who is address to look up /// @return A boolean of minter role function isMinter(address _who) public view returns (bool) { return minters[_who]; } /// @notice Adds the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, true); } /// @notice Deletes the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, false); } /// @notice Adds the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, true); } /// @notice Deletes the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, false); } /// @notice Changes the owner role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setOwner(address _who, bool _flag) private returns (bool) { require(owners[_who] != _flag); owners[_who] = _flag; if (_flag) { emit AddOwner(_who); } else { emit DeleteOwner(_who); } return true; } /// @notice Changes the minter role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setMinter(address _who, bool _flag) private returns (bool) { require(minters[_who] != _flag); minters[_who] = _flag; if (_flag) { emit AddMinter(_who); } else { emit DeleteMinter(_who); } return true; } } interface IMintableToken { function mint(address _to, uint256 _amount) external returns (bool); } /// @title Very simplified implementation of Token Bucket Algorithm to secure token minting /// @author Abha Mai <[email protected]> /// @notice Works with tokens implemented Mintable interface /// @dev Transfer ownership/minting role to contract and execute mint over ICOBucket proxy to secure contract ICOBucket is RBACMixin { using SafeMath for uint; /// @notice Limit maximum amount of available for minting tokens when bucket is full /// @dev Should be enough to mint tokens with proper speed but less enough to prevent overminting in case of losing pkey uint256 public size; /// @notice Bucket refill rate /// @dev Tokens per second (based on block.timestamp). Amount without decimals (in smallest part of token) uint256 public rate; /// @notice Stored time of latest minting /// @dev Each successful call of minting function will update field with call timestamp uint256 public lastMintTime; /// @notice Left tokens in bucket on time of latest minting uint256 public leftOnLastMint; /// @notice Reference of Mintable token /// @dev Setup in contructor phase and never change in future IMintableToken public token; /// @notice Token Bucket leak event fires on each minting /// @param to is address of target tokens holder /// @param left is amount of tokens available in bucket after leak event Leak(address indexed to, uint256 left); /// ICO SECTION /// @notice A token price uint256 public tokenCost; /// @notice Allow only whitelisted wallets to purchase mapping(address => bool) public whiteList; /// @notice Main wallet all funds are transferred to address public wallet; /// @notice Main wallet all funds are transferred to uint256 public bonus; /// @notice Minimum amount of tokens can be purchased uint256 public minimumTokensForPurchase; /// @notice A helper modifier onlyWhiteList { require(whiteList[msg.sender]); _; } /// END ICO SECTION /// @param _token is address of Mintable token /// @param _size initial size of token bucket /// @param _rate initial refill rate (tokens/sec) constructor (address _token, uint256 _size, uint256 _rate, uint256 _cost, address _wallet, uint256 _bonus, uint256 _minimum) public { token = IMintableToken(_token); size = _size; rate = _rate; leftOnLastMint = _size; tokenCost = _cost; wallet = _wallet; bonus = _bonus; minimumTokensForPurchase = _minimum; } /// @notice Change size of bucket /// @dev Require owner role to call /// @param _size is new size of bucket /// @return A boolean that indicates if the operation was successful. function setSize(uint256 _size) public onlyOwner returns (bool) { size = _size; return true; } /// @notice Change refill rate of bucket /// @dev Require owner role to call /// @param _rate is new refill rate of bucket /// @return A boolean that indicates if the operation was successful. function setRate(uint256 _rate) public onlyOwner returns (bool) { rate = _rate; return true; } /// @notice Change size and refill rate of bucket /// @dev Require owner role to call /// @param _size is new size of bucket /// @param _rate is new refill rate of bucket /// @return A boolean that indicates if the operation was successful. function setSizeAndRate(uint256 _size, uint256 _rate) public onlyOwner returns (bool) { return setSize(_size) && setRate(_rate); } /// @notice Function to calculate and get available in bucket tokens /// @return An amount of available tokens in bucket function availableTokens() public view returns (uint) { // solium-disable-next-line security/no-block-members uint256 timeAfterMint = now.sub(lastMintTime); uint256 refillAmount = rate.mul(timeAfterMint).add(leftOnLastMint); return size < refillAmount ? size : refillAmount; } /// ICO METHODS function addToWhiteList(address _address) public onlyMinter { whiteList[_address] = true; } function removeFromWhiteList(address _address) public onlyMinter { whiteList[_address] = false; } function setWallet(address _wallet) public onlyOwner { wallet = _wallet; } function setBonus(uint256 _bonus) public onlyOwner { bonus = _bonus; } function setMinimumTokensForPurchase(uint256 _minimum) public onlyOwner { minimumTokensForPurchase = _minimum; } /// @notice Purchase function mints tokens /// @return A boolean that indicates if the operation was successful. function () public payable onlyWhiteList { uint256 tokensAmount = tokensAmountForPurchase(); uint256 available = availableTokens(); uint256 minimum = minimumTokensForPurchase; require(tokensAmount <= available); require(tokensAmount >= minimum); // transfer all funcds to external multisig wallet wallet.transfer(msg.value); leftOnLastMint = available.sub(tokensAmount); lastMintTime = now; // solium-disable-line security/no-block-members require(token.mint(msg.sender, tokensAmount)); } function tokensAmountForPurchase() private constant returns(uint256) { return msg.value.mul(10 ** 18) .div(tokenCost) .mul(100 + bonus) .div(100); } }
Adds the owner role to provided address Requires owner role to interact _who is address to add role return A boolean that indicates if the operation was successful.
function addOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, true); }
1,465,550
pragma solidity ^0.4.18; // File: contracts/zeppelin-solidity-1.4/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/BRDCrowdsaleAuthorizer.sol /** * Contract BRDCrowdsaleAuthorizer is used by the crowdsale website * to autorize wallets to participate in the crowdsale. Because all * participants must go through the KYC/AML phase, only accounts * listed in this contract may contribute to the crowdsale */ contract BRDCrowdsaleAuthorizer is Ownable { // these accounts are authorized to participate in the crowdsale mapping (address => bool) internal authorizedAccounts; // these accounts are authorized to authorize accounts mapping (address => bool) internal authorizers; // emitted when a new account is authorized event Authorized(address indexed _to); // add an authorizer to the authorizers mapping. the _newAuthorizer will // be able to add other authorizers and authorize crowdsale participants function addAuthorizer(address _newAuthorizer) onlyOwnerOrAuthorizer public { // allow the provided address to authorize accounts authorizers[_newAuthorizer] = true; } // remove an authorizer from the authorizers mapping. the _bannedAuthorizer will // no longer have permission to do anything on this contract function removeAuthorizer(address _bannedAuthorizer) onlyOwnerOrAuthorizer public { // only attempt to remove the authorizer if they are currently authorized require(authorizers[_bannedAuthorizer]); // remove the authorizer delete authorizers[_bannedAuthorizer]; } // allow an account to participate in the crowdsale function authorizeAccount(address _newAccount) onlyOwnerOrAuthorizer public { if (!authorizedAccounts[_newAccount]) { // allow the provided account to participate in the crowdsale authorizedAccounts[_newAccount] = true; // emit the Authorized event Authorized(_newAccount); } } // returns whether or not the provided _account is an authorizer function isAuthorizer(address _account) constant public returns (bool _isAuthorizer) { return msg.sender == owner || authorizers[_account] == true; } // returns whether or not the provided _account is authorized to participate in the crowdsale function isAuthorized(address _account) constant public returns (bool _authorized) { return authorizedAccounts[_account] == true; } // allow only the contract creator or one of the authorizers to do this modifier onlyOwnerOrAuthorizer() { require(msg.sender == owner || authorizers[msg.sender]); _; } } // File: contracts/zeppelin-solidity-1.4/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/BRDLockup.sol /** * Contract BRDLockup keeps track of a vesting schedule for pre-sold tokens. * Pre-sold tokens are rewarded up to `numIntervals` times separated by an * `interval` of time. An equal amount of tokens (`allocation` divided by `numIntervals`) * is marked for reward each `interval`. * * The owner of the contract will call processInterval() which will * update the allocation state. The owner of the contract should then * read the allocation data and reward the beneficiaries. */ contract BRDLockup is Ownable { using SafeMath for uint256; // Allocation stores info about how many tokens to reward a beneficiary account struct Allocation { address beneficiary; // account to receive rewards uint256 allocation; // total allocated tokens uint256 remainingBalance; // remaining balance after the current interval uint256 currentInterval; // the current interval for the given reward uint256 currentReward; // amount to be rewarded during the current interval } // the allocation state Allocation[] public allocations; // the date at which allocations begin unlocking uint256 public unlockDate; // the current unlock interval uint256 public currentInterval; // the interval at which allocations will be rewarded uint256 public intervalDuration; // the number of total reward intervals, zero indexed uint256 public numIntervals; event Lock(address indexed _to, uint256 _amount); event Unlock(address indexed _to, uint256 _amount); // constructor // @param _crowdsaleEndDate - the date the crowdsale ends function BRDLockup(uint256 _crowdsaleEndDate, uint256 _numIntervals, uint256 _intervalDuration) public { unlockDate = _crowdsaleEndDate; numIntervals = _numIntervals; intervalDuration = _intervalDuration; currentInterval = 0; } // update the allocation storage remaining balances function processInterval() onlyOwner public returns (bool _shouldProcessRewards) { // ensure the time interval is correct bool _correctInterval = now >= unlockDate && now.sub(unlockDate) > currentInterval.mul(intervalDuration); bool _validInterval = currentInterval < numIntervals; if (!_correctInterval || !_validInterval) return false; // advance the current interval currentInterval = currentInterval.add(1); // number of iterations to read all allocations uint _allocationsIndex = allocations.length; // loop through every allocation for (uint _i = 0; _i < _allocationsIndex; _i++) { // the current reward for the allocation at index `i` uint256 _amountToReward; // if we are at the last interval, the reward amount is the entire remaining balance if (currentInterval == numIntervals) { _amountToReward = allocations[_i].remainingBalance; } else { // otherwise the reward amount is the total allocation divided by the number of intervals _amountToReward = allocations[_i].allocation.div(numIntervals); } // update the allocation storage allocations[_i].currentReward = _amountToReward; } return true; } // the total number of allocations function numAllocations() constant public returns (uint) { return allocations.length; } // the amount allocated for beneficiary at `_index` function allocationAmount(uint _index) constant public returns (uint256) { return allocations[_index].allocation; } // reward the beneficiary at `_index` function unlock(uint _index) onlyOwner public returns (bool _shouldReward, address _beneficiary, uint256 _rewardAmount) { // ensure the beneficiary is not rewarded twice during the same interval if (allocations[_index].currentInterval < currentInterval) { // record the currentInterval so the above check is useful allocations[_index].currentInterval = currentInterval; // subtract the reward from their remaining balance allocations[_index].remainingBalance = allocations[_index].remainingBalance.sub(allocations[_index].currentReward); // emit event Unlock(allocations[_index].beneficiary, allocations[_index].currentReward); // return value _shouldReward = true; } else { // return value _shouldReward = false; } // return values _rewardAmount = allocations[_index].currentReward; _beneficiary = allocations[_index].beneficiary; } // add a new allocation to the lockup function pushAllocation(address _beneficiary, uint256 _numTokens) onlyOwner public { require(now < unlockDate); allocations.push( Allocation( _beneficiary, _numTokens, _numTokens, 0, 0 ) ); Lock(_beneficiary, _numTokens); } } // File: contracts/zeppelin-solidity-1.4/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/zeppelin-solidity-1.4/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/zeppelin-solidity-1.4/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/zeppelin-solidity-1.4/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * 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) { 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) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/zeppelin-solidity-1.4/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is 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(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/BRDToken.sol contract BRDToken is MintableToken { using SafeMath for uint256; string public name = "Bread Token"; string public symbol = "BRD"; uint256 public decimals = 18; // override StandardToken#transferFrom // ensures that minting has finished or the message sender is the token owner function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(mintingFinished || msg.sender == owner); return super.transferFrom(_from, _to, _value); } // override StandardToken#transfer // ensures the minting has finished or the message sender is the token owner function transfer(address _to, uint256 _value) public returns (bool) { require(mintingFinished || msg.sender == owner); return super.transfer(_to, _value); } } // File: contracts/zeppelin-solidity-1.4/Crowdsale.sol /** * @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 MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // 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 view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/zeppelin-solidity-1.4/FinalizableCrowdsale.sol /** * @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 { } } // File: contracts/BRDCrowdsale.sol contract BRDCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // maximum amount of wei raised during this crowdsale uint256 public cap; // minimum per-participant wei contribution uint256 public minContribution; // maximum per-participant wei contribution uint256 public maxContribution; // how many token unites the owner gets per buyer wei uint256 public ownerRate; // number of tokens per 100 to lock up in lockupTokens() uint256 public bonusRate; // crowdsale authorizer contract determines who can participate BRDCrowdsaleAuthorizer public authorizer; // the lockup contract holds presale authorization amounts BRDLockup public lockup; // constructor function BRDCrowdsale( uint256 _cap, // maximum wei raised uint256 _minWei, // minimum per-contributor wei uint256 _maxWei, // maximum per-contributor wei uint256 _startTime, // crowdsale start time uint256 _endTime, // crowdsale end time uint256 _rate, // tokens per wei uint256 _ownerRate, // owner tokens per buyer wei uint256 _bonusRate, // percentage of tokens to lockup address _wallet) // target funds wallet Crowdsale(_startTime, _endTime, _rate, _wallet) public { require(_cap > 0); cap = _cap; minContribution = _minWei; maxContribution = _maxWei; ownerRate = _ownerRate; bonusRate = _bonusRate; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool _capReached = weiRaised >= cap; return super.hasEnded() || _capReached; } // @return true if the crowdsale has started function hasStarted() public constant returns (bool) { return now > startTime; } // overriding Crowdsale#buyTokens // mints the ownerRate of tokens in addition to calling the super method function buyTokens(address _beneficiary) public payable { // call the parent method to mint tokens to the beneficiary super.buyTokens(_beneficiary); // calculate the owner share of tokens uint256 _ownerTokens = msg.value.mul(ownerRate); // mint the owner share and send to the owner wallet token.mint(wallet, _ownerTokens); } // mints _amount tokens to the _beneficiary minus the bonusRate // tokens to be locked up via the lockup contract. locked up tokens // are sent to the contract and may be unlocked according to // the lockup configuration after the sale ends function lockupTokens(address _beneficiary, uint256 _amount) onlyOwner public { require(!isFinalized); // calculate the owner share of tokens uint256 _ownerTokens = ownerRate.mul(_amount).div(rate); // mint the owner share and send to the owner wallet token.mint(wallet, _ownerTokens); // calculate the amount of tokens to be locked up uint256 _lockupTokens = bonusRate.mul(_amount).div(100); // create the locked allocation in the lockup contract lockup.pushAllocation(_beneficiary, _lockupTokens); // mint locked tokens to the crowdsale contract to later be unlocked token.mint(this, _lockupTokens); // the non-bonus tokens are immediately rewarded uint256 _remainder = _amount.sub(_lockupTokens); token.mint(_beneficiary, _remainder); } // unlocks tokens from the token lockup contract. no tokens are held by // the lockup contract, just the amounts and times that tokens should be rewarded. // the tokens are held by the crowdsale contract function unlockTokens() onlyOwner public returns (bool _didIssueRewards) { // attempt to process the interval. it update the allocation bookkeeping // and will only return true when the interval should be processed if (!lockup.processInterval()) return false; // the total number of allocations uint _numAllocations = lockup.numAllocations(); // for every allocation, attempt to unlock the reward for (uint _i = 0; _i < _numAllocations; _i++) { // attempt to unlock the reward var (_shouldReward, _to, _amount) = lockup.unlock(_i); // if the beneficiary should be rewarded, send them tokens if (_shouldReward) { token.transfer(_to, _amount); } } return true; } // sets the authorizer contract if the crowdsale hasn't started function setAuthorizer(BRDCrowdsaleAuthorizer _authorizer) onlyOwner public { require(!hasStarted()); authorizer = _authorizer; } // sets the lockup contract if the crowdsale hasn't started function setLockup(BRDLockup _lockup) onlyOwner public { require(!hasStarted()); lockup = _lockup; } // sets the token contract if the crowdsale hasn't started function setToken(BRDToken _token) onlyOwner public { require(!hasStarted()); token = _token; } // allows maxContribution to be modified function setMaxContribution(uint256 _newMaxContribution) onlyOwner public { maxContribution = _newMaxContribution; } // allows endTime to be modified function setEndTime(uint256 _newEndTime) onlyOwner public { endTime = _newEndTime; } // overriding Crowdsale#createTokenContract function createTokenContract() internal returns (MintableToken) { // set the token to null initially // call setToken() above to set the actual token address return BRDToken(address(0)); } // overriding FinalizableCrowdsale#finalization // finalizes minting for the token contract, disabling further minting function finalization() internal { // end minting token.finishMinting(); // issue the first lockup reward unlockTokens(); super.finalization(); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if crowdsale participants can buy at the moment // checks whether the cap has not been reached, the purchaser has // been authorized, and their contribution is within the min/max // thresholds function validPurchase() internal constant returns (bool) { bool _withinCap = weiRaised.add(msg.value) <= cap; bool _isAuthorized = authorizer.isAuthorized(msg.sender); bool _isMin = msg.value >= minContribution; uint256 _alreadyContributed = token.balanceOf(msg.sender).div(rate); bool _withinMax = msg.value.add(_alreadyContributed) <= maxContribution; return super.validPurchase() && _withinCap && _isAuthorized && _isMin && _withinMax; } }
allows maxContribution to be modified
function setMaxContribution(uint256 _newMaxContribution) onlyOwner public { maxContribution = _newMaxContribution; }
12,589,090
./full_match/5/0x998bf0Eb2ee683020eC906FAF16f81Fc22641435/sources/contracts/core/connext/helpers/OZERC20.sol
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `_spender` cannot be the zero address. - `_spender` must have allowance for the caller of at least `_subtractedValue`./
function decreaseAllowance(address _spender, uint256 _subtractedValue) public virtual returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender].sub(_subtractedValue, "ERC20: decreased allowance below zero") ); return true; }
1,904,030
./full_match/1/0xBc5FbB45A2bbB64d9B2EeBFa327284a35d5C5865/sources/src/SignedMintAuthorizer.sol
@inheritdoc IAuthorizeMints reverts when signature is not valid or recovered signer is not trustedtodo consider using an ERC712 typed signature here signedAuthorization contains encoded SignedMintAuthorization that a trusted signer has agreed upon
function authorizeMint(address minter, address to, bytes memory signedAuthorization) external view override returns (bool) { SignedMintAuthorization memory auth = abi.decode(signedAuthorization, (SignedMintAuthorization)); bytes32 signedHash = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(minter, to, auth.reservationId, auth.tokenUri))); (address signer,) = ECDSA.tryRecover(signedHash, auth.authorization); return trustedSigners[signer]; }
16,402,622
// SPDX-License-Identifier: GPL-3.0-or-later // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IDai.sol pragma solidity ^0.6.10; interface IDai is IERC20 { function nonces(address user) external view returns (uint256); function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function addDelegate(address) external; function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; function delegated(address, address) external view returns (bool); } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function isMature() external view returns(bool); function maturity() external view returns(uint); function chi0() external view returns(uint); function rate0() external view returns(uint); function chiGrowth() external view returns(uint); function rateGrowth() external view returns(uint); function mature() external; function unlocked() external view returns (uint); function mint(address, uint) external; function burn(address, uint) external; function flashMint(uint, bytes calldata) external; function redeem(address, address, uint256) external returns (uint256); // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IPool.sol pragma solidity ^0.6.10; interface IPool is IDelegable, IERC20, IERC2612 { function dai() external view returns(IERC20); function fyDai() external view returns(IFYDai); function getDaiReserves() external view returns(uint128); function getFYDaiReserves() external view returns(uint128); function sellDai(address from, address to, uint128 daiIn) external returns(uint128); function buyDai(address from, address to, uint128 daiOut) external returns(uint128); function sellFYDai(address from, address to, uint128 fyDaiIn) external returns(uint128); function buyFYDai(address from, address to, uint128 fyDaiOut) external returns(uint128); function sellDaiPreview(uint128 daiIn) external view returns(uint128); function buyDaiPreview(uint128 daiOut) external view returns(uint128); function sellFYDaiPreview(uint128 fyDaiIn) external view returns(uint128); function buyFYDaiPreview(uint128 fyDaiOut) external view returns(uint128); function mint(address from, address to, uint256 daiOffered) external returns (uint256); function burn(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; /// @dev interface for the chai contract /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IChai { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function approve(address usr, uint wad) external returns (bool); function dai(address usr) external returns (uint wad); function join(address dst, uint wad) external; function exit(address src, uint wad) external; function draw(address src, uint wad) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function nonces(address account) external view returns (uint256); } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the vat contract from MakerDAO /// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md interface IVat { // function can(address, address) external view returns (uint); function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint); // function dai(address) external view returns (uint); function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; function move(address, address, uint) external; function flux(bytes32, address, address, uint) external; } // File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns (bool) ; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20 interface IGemJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai interface IDaiJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; /// @dev interface for the pot contract from MakerDao /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IPot { function chi() external view returns (uint256); function pie(address) external view returns (uint256); // Not a function, but a public variable. function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function debt() external view returns(uint256); function savings() external view returns(uint256); function pushDai(address user, uint256 dai) external; function pullDai(address user, uint256 dai) external; function pushChai(address user, uint256 chai) external; function pullChai(address user, uint256 chai) external; function pushWeth(address to, uint256 weth) external; function pullWeth(address to, uint256 weth) external; function shutdown() external; function live() external view returns(bool); function vat() external view returns (IVat); function weth() external view returns (IWeth); function dai() external view returns (IERC20); function daiJoin() external view returns (IDaiJoin); function wethJoin() external view returns (IGemJoin); function pot() external view returns (IPot); function chai() external view returns (IChai); } // File: contracts/interfaces/IController.sol pragma solidity ^0.6.10; interface IController is IDelegable { function treasury() external view returns (ITreasury); function series(uint256) external view returns (IFYDai); function seriesIterator(uint256) external view returns (uint256); function totalSeries() external view returns (uint256); function containsSeries(uint256) external view returns (bool); function posted(bytes32, address) external view returns (uint256); function locked(bytes32, address) external view returns (uint256); function debtFYDai(bytes32, uint256, address) external view returns (uint256); function debtDai(bytes32, uint256, address) external view returns (uint256); function totalDebtDai(bytes32, address) external view returns (uint256); function isCollateralized(bytes32, address) external view returns (bool); function inDai(bytes32, uint256, uint256) external view returns (uint256); function inFYDai(bytes32, uint256, uint256) external view returns (uint256); function erase(bytes32, address) external returns (uint256, uint256); function shutdown() external; function post(bytes32, address, address, uint256) external; function withdraw(bytes32, address, address, uint256) external; function borrow(bytes32, uint256, address, address, uint256) external; function repayFYDai(bytes32, uint256, address, address, uint256) external returns (uint256); function repayDai(bytes32, uint256, address, address, uint256) external returns (uint256); } // File: @openzeppelin/contracts/math/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/helpers/DecimalMath.sol pragma solidity ^0.6.10; /// @dev Implements simple fixed point math mul and div operations for 27 decimals. contract DecimalMath { using SafeMath for uint256; uint256 constant public UNIT = 1e27; /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(UNIT); } /// @dev Divides x between y, assuming they are both fixed point with 27 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); } /// @dev Multiplies x and y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); } /// @dev Divides x between y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function divdrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(UNIT); return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); } } // File: contracts/peripheral/PoolProxy.sol pragma solidity ^0.6.10; library SafeCast { /// @dev Safe casting from uint256 to uint128 function toUint128(uint256 x) internal pure returns(uint128) { require( x <= type(uint128).max, "YieldProxy: Cast overflow" ); return uint128(x); } /// @dev Safe casting from uint256 to int256 function toInt256(uint256 x) internal pure returns(int256) { require( x <= uint256(type(int256).max), "YieldProxy: Cast overflow" ); return int256(x); } } contract PoolProxy is DecimalMath { using SafeCast for uint256; IDai public dai; IChai public chai; IController public controller; IPool[] public pools; mapping (address => bool) public poolsMap; bytes32 public constant CHAI = "CHAI"; constructor(address controller_, IPool[] memory _pools) public { controller = IController(controller_); ITreasury treasury = controller.treasury(); dai = IDai(address(treasury.dai())); chai = treasury.chai(); // for repaying debt dai.approve(address(treasury), uint(-1)); // for posting to the controller chai.approve(address(treasury), uint(-1)); // for converting DAI to CHAI dai.approve(address(chai), uint(-1)); // allow all the pools to pull FYDai/dai from us for LPing for (uint i = 0 ; i < _pools.length; i++) { dai.approve(address(_pools[i]), uint(-1)); _pools[i].fyDai().approve(address(_pools[i]), uint(-1)); poolsMap[address(_pools[i])]= true; } pools = _pools; } /// @dev Unpack r, s and v from a `bytes` signature function unpack(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } function authorizeForAdding(bytes memory daiSig, bytes memory controllerSig) public { bytes32 r; bytes32 s; uint8 v; if (daiSig.length > 0) { (r, s, v) = unpack(daiSig); dai.permit(msg.sender, address(this), dai.nonces(msg.sender), uint(-1), true, v, r, s); } if (controllerSig.length > 0) { (r, s, v) = unpack(controllerSig); controller.addDelegateBySignature(msg.sender, address(this), uint(-1), v, r, s); } } function authorizeForRemoving(IPool pool, bytes memory controllerSig, bytes memory poolSig) public { onlyKnownPool(pool); bytes32 r; bytes32 s; uint8 v; if (controllerSig.length > 0) { (r, s, v) = unpack(controllerSig); controller.addDelegateBySignature(msg.sender, address(this), uint(-1), v, r, s); } if (poolSig.length > 0) { (r, s, v) = unpack(poolSig); pool.addDelegateBySignature(msg.sender, address(this), uint(-1), v, r, s); } } /// @dev Mints liquidity with provided Dai by borrowing fyDai with some of the Dai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the dai transfer with `dai.approve(daiUsed)` /// @param daiUsed amount of Dai to use to mint liquidity. /// @param maxFYDai maximum amount of fyDai to be borrowed to mint liquidity. /// @param daiSig packed signature for permit of dai transfers to this proxy. /// @param controllerSig packed signature for delegation of this proxy in the controller. /// @return The amount of liquidity tokens minted. function addLiquidityWithSignature( IPool pool, uint256 daiUsed, uint256 maxFYDai, bytes memory daiSig, bytes memory controllerSig ) external returns (uint256) { onlyKnownPool(pool); authorizeForAdding(daiSig, controllerSig); return addLiquidity(pool, daiUsed, maxFYDai); } /// @dev Burns tokens and sells Dai proceedings for fyDai. Pays as much debt as possible, then sells back any remaining fyDai for Dai. Then returns all Dai, and all unlocked Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` <-- It actually doesn't. /// @param poolTokens amount of pool tokens to burn. /// @param minimumDaiPrice minimum fyDai/Dai price to be accepted when internally selling Dai. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. /// @param controllerSig packed signature for delegation of this proxy in the controller. /// @param poolSig packed signature for delegation of this proxy in a pool. function removeLiquidityEarlyDaiPoolWithSignature( IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice, bytes memory controllerSig, bytes memory poolSig ) public { onlyKnownPool(pool); authorizeForRemoving(pool, controllerSig, poolSig); removeLiquidityEarlyDaiPool(pool, poolTokens, minimumDaiPrice, minimumFYDaiPrice); } /// @dev Burns tokens and repays debt with proceedings. Sells any excess fyDai for Dai, then returns all Dai, and all unlocked Chai. /// @param poolTokens amount of pool tokens to burn. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. /// @param controllerSig packed signature for delegation of this proxy in the controller. /// @param poolSig packed signature for delegation of this proxy in a pool. function removeLiquidityEarlyDaiFixedWithSignature( IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice, bytes memory controllerSig, bytes memory poolSig ) public { onlyKnownPool(pool); authorizeForRemoving(pool, controllerSig, poolSig); removeLiquidityEarlyDaiFixed(pool, poolTokens, minimumFYDaiPrice); } /// @dev Burns tokens and repays fyDai debt after Maturity. /// @param poolTokens amount of pool tokens to burn. /// @param controllerSig packed signature for delegation of this proxy in the controller. /// @param poolSig packed signature for delegation of this proxy in a pool. function removeLiquidityMatureWithSignature( IPool pool, uint256 poolTokens, bytes memory controllerSig, bytes memory poolSig ) external { onlyKnownPool(pool); authorizeForRemoving(pool, controllerSig, poolSig); removeLiquidityMature(pool, poolTokens); } /// @dev Mints liquidity with provided Dai by borrowing fyDai with some of the Dai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the dai transfer with `dai.approve(daiUsed)` /// @param daiUsed amount of Dai to use to mint liquidity. /// @param maxFYDai maximum amount of fyDai to be borrowed to mint liquidity. /// @return The amount of liquidity tokens minted. function addLiquidity(IPool pool, uint256 daiUsed, uint256 maxFYDai) public returns (uint256) { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); require(fyDai.isMature() != true, "YieldProxy: Only before maturity"); require(dai.transferFrom(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed"); // calculate needed fyDai uint256 daiReserves = dai.balanceOf(address(pool)); uint256 fyDaiReserves = fyDai.balanceOf(address(pool)); uint256 daiToAdd = daiUsed.mul(daiReserves).div(fyDaiReserves.add(daiReserves)); uint256 daiToConvert = daiUsed.sub(daiToAdd); require( daiToConvert <= maxFYDai, "YieldProxy: maxFYDai exceeded" ); // 1 Dai == 1 fyDai // convert dai to chai and borrow needed fyDai chai.join(address(this), daiToConvert); // look at the balance of chai in dai to avoid rounding issues uint256 toBorrow = chai.dai(address(this)); controller.post(CHAI, address(this), msg.sender, chai.balanceOf(address(this))); controller.borrow(CHAI, fyDai.maturity(), msg.sender, address(this), toBorrow); // mint liquidity tokens return pool.mint(address(this), msg.sender, daiToAdd); } /// @dev Burns tokens and sells Dai proceedings for fyDai. Pays as much debt as possible, then sells back any remaining fyDai for Dai. Then returns all Dai, and if there is no debt in the Controller, all posted Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. /// @param minimumDaiPrice minimum fyDai/Dai price to be accepted when internally selling Dai. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. function removeLiquidityEarlyDaiPool(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) public { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); // Exchange Dai for fyDai to pay as much debt as possible uint256 fyDaiBought = pool.sellDai(address(this), address(this), daiObtained.toUint128()); require( fyDaiBought >= muld(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.add(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets(); } /// @dev Burns tokens and repays debt with proceedings. Sells any excess fyDai for Dai, then returns all Dai, and if there is no debt in the Controller, all posted Chai. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. /// @param minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. function removeLiquidityEarlyDaiFixed(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) public { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained); } } else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets(); } /// @dev Burns tokens and repays fyDai debt after Maturity. /// Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` /// Caller must have approved the liquidity burn with `pool.approve(poolTokens)` /// @param poolTokens amount of pool tokens to burn. function removeLiquidityMature(IPool pool, uint256 poolTokens) public { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); if (fyDaiObtained > 0) { daiObtained = daiObtained.add(fyDai.redeem(address(this), address(this), fyDaiObtained)); } // Repay debt if (daiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { controller.repayDai(CHAI, maturity, address(this), msg.sender, daiObtained); } withdrawAssets(); } /// @dev Return to caller all posted chai if there is no debt, converted to dai, plus any dai remaining in the contract. function withdrawAssets() internal { uint256 posted = controller.posted(CHAI, msg.sender); uint256 locked = controller.locked(CHAI, msg.sender); require (posted >= locked, "YieldProxy: Undercollateralized"); controller.withdraw(CHAI, msg.sender, address(this), posted - locked); chai.exit(address(this), chai.balanceOf(address(this))); require(dai.transfer(msg.sender, dai.balanceOf(address(this))), "YieldProxy: Dai Transfer Failed"); } function onlyKnownPool(IPool pool) private view { require(poolsMap[address(pool)], "YieldProxy: Unknown pool"); } }
Burns tokens and sells Dai proceedings for fyDai. Pays as much debt as possible, then sells back any remaining fyDai for Dai. Then returns all Dai, and if there is no debt in the Controller, all posted Chai. Caller must have approved the proxy using`controller.addDelegate(yieldProxy)` and `pool.addDelegate(yieldProxy)` Caller must have approved the liquidity burn with `pool.approve(poolTokens)` poolTokens amount of pool tokens to burn. minimumDaiPrice minimum fyDai/Dai price to be accepted when internally selling Dai. minimumFYDaiPrice minimum Dai/fyDai price to be accepted when internally selling fyDai. Exchange Dai for fyDai to pay as much debt as possible
function removeLiquidityEarlyDaiPool(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) public { onlyKnownPool(pool); IFYDai fyDai = pool.fyDai(); uint256 maturity = fyDai.maturity(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.burn(msg.sender, address(this), poolTokens); uint256 fyDaiBought = pool.sellDai(address(this), address(this), daiObtained.toUint128()); require( fyDaiBought >= muld(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.add(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.debtFYDai(CHAI, maturity, msg.sender) > 0) { fyDaiUsed = controller.repayFYDai(CHAI, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.sub(fyDaiUsed); require( pool.sellFYDai(address(this), address(this), uint128(fyDaiRemaining)) >= muld(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } withdrawAssets();
2,125,898
./partial_match/1/0x59BC239cAb00CADd9b14f299835ae39E8B4B569c/sources/contracts/protocol/libraries/configuration/ReserveConfiguration.sol
Gets the stable rate borrowing state of the reserve self The reserve configuration return The stable rate borrowing state/
function getStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap storage self ) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; }
15,931,728
./partial_match/1/0x1E3A682f5f9BDD87b88D28dc2eC9EDE002bfE95e/sources/vnxManager.sol
Retrieve the number of roles in the contract./
function totalRoles() external view returns(uint256) { return roles.length; }
3,979,000
./full_match/43113/0x9fc79C0e6c0175F2637D4E1371655C5b444b8Bde/sources/contracts/ERC721PresetMinterPauserAutoId_flat.sol
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(); }
7,134,679
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // /** * @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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 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); } } } } // /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // contract HoneycombV3 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many staking tokens the user has provided. uint256 rewardDebt; // Reward debt. uint256 mined; uint256 collected; } struct CollectingInfo { uint256 collectableTime; uint256 amount; bool collected; } // Info of each pool. struct PoolInfo { IERC20 stakingToken; // Address of staking token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that HONEYs distribution occurs. uint256 accHoneyPerShare; // Accumulated HONEYs per share, times 1e12. uint256 totalShares; } struct BatchInfo { uint256 startBlock; uint256 endBlock; uint256 honeyPerBlock; uint256 totalAllocPoint; } // Info of each batch BatchInfo[] public batchInfo; // Info of each pool at specified batch. mapping (uint256 => PoolInfo[]) public poolInfo; // Info of each user at specified batch and pool mapping (uint256 => mapping (uint256 => mapping (address => UserInfo))) public userInfo; mapping (uint256 => mapping (uint256 => mapping (address => CollectingInfo[]))) public collectingInfo; IERC20 public honeyToken; uint256 public collectingDuration = 86400 * 3; uint256 public instantCollectBurnRate = 4000; // 40% address public burnDestination; event Deposit(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 amount); constructor (address _honeyToken, address _burnDestination) public { honeyToken = IERC20(_honeyToken); burnDestination = _burnDestination; } function addBatch(uint256 startBlock, uint256 endBlock, uint256 honeyPerBlock) public onlyOwner { require(endBlock > startBlock, "endBlock should be larger than startBlock"); require(endBlock > block.number, "endBlock should be larger than the current block number"); require(startBlock > block.number, "startBlock should be larger than the current block number"); if (batchInfo.length > 0) { uint256 lastEndBlock = batchInfo[batchInfo.length - 1].endBlock; require(startBlock >= lastEndBlock, "startBlock should be >= the endBlock of the last batch"); } uint256 senderHoneyBalance = honeyToken.balanceOf(address(msg.sender)); uint256 requiredHoney = endBlock.sub(startBlock).mul(honeyPerBlock); require(senderHoneyBalance >= requiredHoney, "insufficient HONEY for the batch"); honeyToken.safeTransferFrom(address(msg.sender), address(this), requiredHoney); batchInfo.push(BatchInfo({ startBlock: startBlock, endBlock: endBlock, honeyPerBlock: honeyPerBlock, totalAllocPoint: 0 })); } function addPool(uint256 batch, IERC20 stakingToken, uint256 multiplier) public onlyOwner { require(batch < batchInfo.length, "batch must exist"); BatchInfo storage targetBatch = batchInfo[batch]; if (targetBatch.startBlock <= block.number && block.number < targetBatch.endBlock) { updateAllPools(batch); } uint256 lastRewardBlock = block.number > targetBatch.startBlock ? block.number : targetBatch.startBlock; batchInfo[batch].totalAllocPoint = targetBatch.totalAllocPoint.add(multiplier); poolInfo[batch].push(PoolInfo({ stakingToken: stakingToken, allocPoint: multiplier, lastRewardBlock: lastRewardBlock, accHoneyPerShare: 0, totalShares: 0 })); } // Return rewardable block count over the given _from to _to block. function getPendingBlocks(uint256 batch, uint256 from, uint256 to) public view returns (uint256) { require(batch < batchInfo.length, "batch must exist"); BatchInfo storage targetBatch = batchInfo[batch]; if (to < targetBatch.startBlock) { return 0; } if (to > targetBatch.endBlock) { if (from > targetBatch.endBlock) { return 0; } else { return targetBatch.endBlock.sub(from); } } else { return to.sub(from); } } // View function to see pending HONEYs on frontend. function minedHoney(uint256 batch, uint256 pid, address account) external view returns (uint256) { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; if (block.number < targetBatch.startBlock) { return 0; } PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][account]; uint256 accHoneyPerShare = pool.accHoneyPerShare; if (block.number > pool.lastRewardBlock && pool.totalShares != 0) { uint256 pendingBlocks = getPendingBlocks(batch, pool.lastRewardBlock, block.number); uint256 honeyReward = pendingBlocks.mul(targetBatch.honeyPerBlock).mul(pool.allocPoint).div(targetBatch.totalAllocPoint); accHoneyPerShare = accHoneyPerShare.add(honeyReward.mul(1e12).div(pool.totalShares)); } return user.amount.mul(accHoneyPerShare).div(1e12).sub(user.rewardDebt).add(user.mined); } function updateAllPools(uint256 batch) public { require(batch < batchInfo.length, "batch must exist"); uint256 length = poolInfo[batch].length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(batch, pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 batch, uint256 pid) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; PoolInfo storage pool = poolInfo[batch][pid]; if (block.number < targetBatch.startBlock || block.number <= pool.lastRewardBlock || pool.lastRewardBlock > targetBatch.endBlock) { return; } if (pool.totalShares == 0) { pool.lastRewardBlock = block.number; return; } uint256 pendingBlocks = getPendingBlocks(batch, pool.lastRewardBlock, block.number); uint256 honeyReward = pendingBlocks.mul(targetBatch.honeyPerBlock).mul(pool.allocPoint).div(targetBatch.totalAllocPoint); pool.accHoneyPerShare = pool.accHoneyPerShare.add(honeyReward.mul(1e12).div(pool.totalShares)); pool.lastRewardBlock = block.number; } // Deposit staking tokens for HONEY allocation. function deposit(uint256 batch, uint256 pid, uint256 amount) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; require(block.number < targetBatch.endBlock, "batch ended"); PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][msg.sender]; // 1. Update pool.accHoneyPerShare updatePool(batch, pid); // 2. Transfer pending HONEY to user if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accHoneyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { addToMined(batch, pid, msg.sender, pending); } } // 3. Transfer Staking Token from user to honeycomb if (amount > 0) { pool.stakingToken.safeTransferFrom(address(msg.sender), address(this), amount); user.amount = user.amount.add(amount); } // 4. Update user.rewardDebt pool.totalShares = pool.totalShares.add(amount); user.rewardDebt = user.amount.mul(pool.accHoneyPerShare).div(1e12); emit Deposit(msg.sender, batch, pid, amount); } // Withdraw staking tokens. function withdraw(uint256 batch, uint256 pid, uint256 amount) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); UserInfo storage user = userInfo[batch][pid][msg.sender]; require(user.amount >= amount, "insufficient balance"); // 1. Update pool.accHoneyPerShare updatePool(batch, pid); // 2. Transfer pending HONEY to user PoolInfo storage pool = poolInfo[batch][pid]; uint256 pending = user.amount.mul(pool.accHoneyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { addToMined(batch, pid, msg.sender, pending); } // 3. Transfer Staking Token from honeycomb to user pool.stakingToken.safeTransfer(address(msg.sender), amount); user.amount = user.amount.sub(amount); // 4. Update user.rewardDebt pool.totalShares = pool.totalShares.sub(amount); user.rewardDebt = user.amount.mul(pool.accHoneyPerShare).div(1e12); emit Withdraw(msg.sender, batch, pid, amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 batch, uint256 pid) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][msg.sender]; pool.stakingToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, batch, pid, user.amount); user.amount = 0; user.rewardDebt = 0; } function migrate(uint256 toBatch, uint256 toPid, uint256 amount, uint256 fromBatch, uint256 fromPid) public { require(toBatch < batchInfo.length, "target batch must exist"); require(toPid < poolInfo[toBatch].length, "target pool must exist"); require(fromBatch < batchInfo.length, "source batch must exist"); require(fromPid < poolInfo[fromBatch].length, "source pool must exist"); BatchInfo storage targetBatch = batchInfo[toBatch]; require(block.number < targetBatch.endBlock, "batch ended"); UserInfo storage userFrom = userInfo[fromBatch][fromPid][msg.sender]; if (userFrom.amount > 0) { PoolInfo storage poolFrom = poolInfo[fromBatch][fromPid]; PoolInfo storage poolTo = poolInfo[toBatch][toPid]; require(address(poolFrom.stakingToken) == address(poolTo.stakingToken), "must be the same token"); withdraw(fromBatch, fromPid, amount); deposit(toBatch, toPid, amount); } } // Safe honey transfer function, just in case if rounding error causes pool to not have enough HONEYs. function safeHoneyTransfer(uint256 batch, uint256 pid, address to, uint256 amount) internal { uint256 honeyBal = honeyToken.balanceOf(address(this)); require(honeyBal > 0, "insufficient HONEY balance"); UserInfo storage user = userInfo[batch][pid][to]; if (amount > honeyBal) { honeyToken.transfer(to, honeyBal); user.collected = user.collected.add(honeyBal); } else { honeyToken.transfer(to, amount); user.collected = user.collected.add(amount); } } function addToMined(uint256 batch, uint256 pid, address account, uint256 amount) internal { UserInfo storage user = userInfo[batch][pid][account]; user.mined = user.mined.add(amount); } function startCollecting(uint256 batch, uint256 pid) external { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); withdraw(batch, pid, 0); UserInfo storage user = userInfo[batch][pid][msg.sender]; CollectingInfo[] storage collecting = collectingInfo[batch][pid][msg.sender]; if (user.mined > 0) { collecting.push(CollectingInfo({ collectableTime: block.timestamp + collectingDuration, amount: user.mined, collected: false })); user.mined = 0; } } function collectingHoney(uint256 batch, uint256 pid, address account) external view returns (uint256) { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); CollectingInfo[] storage collecting = collectingInfo[batch][pid][account]; uint256 total = 0; for (uint i = 0; i < collecting.length; ++i) { if (!collecting[i].collected && block.timestamp < collecting[i].collectableTime) { total = total.add(collecting[i].amount); } } return total; } function collectableHoney(uint256 batch, uint256 pid, address account) external view returns (uint256) { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); CollectingInfo[] storage collecting = collectingInfo[batch][pid][account]; uint256 total = 0; for (uint i = 0; i < collecting.length; ++i) { if (!collecting[i].collected && block.timestamp >= collecting[i].collectableTime) { total = total.add(collecting[i].amount); } } return total; } function collectHoney(uint256 batch, uint256 pid) external { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); CollectingInfo[] storage collecting = collectingInfo[batch][pid][msg.sender]; require(collecting.length > 0, "nothing to collect"); uint256 total = 0; for (uint i = 0; i < collecting.length; ++i) { if (!collecting[i].collected && block.timestamp >= collecting[i].collectableTime) { total = total.add(collecting[i].amount); collecting[i].collected = true; } } safeHoneyTransfer(batch, pid, msg.sender, total); } function instantCollectHoney(uint256 batch, uint256 pid) external { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); withdraw(batch, pid, 0); UserInfo storage user = userInfo[batch][pid][msg.sender]; if (user.mined > 0) { uint256 portion = 10000 - instantCollectBurnRate; safeHoneyTransfer(batch, pid, msg.sender, user.mined.mul(portion).div(10000)); honeyToken.transfer(burnDestination, user.mined.mul(instantCollectBurnRate).div(10000)); user.mined = 0; } } function setInstantCollectBurnRate(uint256 value) public onlyOwner { require(value <= 10000, "Value range: 0 ~ 10000"); instantCollectBurnRate = value; } function setCollectingDuration(uint256 value) public onlyOwner { collectingDuration = value; } }
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 batch, uint256 pid) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][msg.sender]; pool.stakingToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, batch, pid, user.amount); user.amount = 0; user.rewardDebt = 0; }
6,263,501
./full_match/11155111/0x311948178664d36A80e5C2248dB2d2b7ab4B525D/sources/project_/contracts/HashStorage.sol
Get the friendly name for a network _notary address of the account who saved the network _networkID network id return networkFriendlyName friendly name for the network
function getNetworkFriendlyName(address _notary, bytes32 _networkID) external view returns (string memory networkFriendlyName) { return networkFriendlyNames[getNetworkUID(_notary, _networkID)]; }
3,791,666
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Interface to the RandomWalkNFT contract. abstract contract IRandomWalkNFT is IERC721 { uint256 public nextTokenId; mapping(uint256 => bytes32) public seeds; function mint() public payable virtual; function withdraw() public virtual; function getMintPrice() public view virtual returns (uint256); } // Interface to IMPISHDAO abstract contract IImpishDAO is IERC20 { function deposit() public payable virtual; } contract ImpishSpiral is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { // Next TokenID uint256 public _tokenIdCounter; // When the last token was minted uint256 public lastMintTime; // Next mint price. Starts at 0.005 ETH uint256 public price = 0.005 ether; // No mints after this much time will result in the end of the mints uint256 public constant MINT_EXPIRY_TIME = 3 * 24 * 3600; // 3 days // Address of the RandomWalkNFT contract IRandomWalkNFT public _rwNFT; // Address of ImpishDAO IImpishDAO public _impishDAO; // Base URI string private _baseTokenURI; // The RNG seed that generates the spiral artwork // tokenId => seed mapping(uint256 => bytes32) public spiralSeeds; // Keep track of minted RandomWalkNFTs to prevent duplicate mints // RandomWalk tokenId => true if minted mapping(uint256 => bool) public mintedRWs; // Entropy bytes32 public entropy; // If the sale has started bool public started = false; // Keep track of the total rewards available uint256 public totalReward = 0; // List of all winners that have claimed their prize // tokenId -> true if winnings have been claimed mapping(uint256 => bool) public winningsClaimed; // The length of each path // tokenID -> Length mapping(uint256 => uint256) public spiralLengths; // Address of the Spirals Episode 2 contract address public spiralBitsContract = address(0); constructor(address _rwNFTaddress, address _impishDAOaddress) ERC721("ImpishSpiral", "SPIRAL") { _rwNFT = IRandomWalkNFT(_rwNFTaddress); _impishDAO = IImpishDAO(_impishDAOaddress); } function startMints() public onlyOwner { require(!started, "Started"); lastMintTime = block.timestamp; started = true; } // Only owner can set the BaseURI function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } // Overrides the one in ERC721.sol function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } // Mint price increases 0.5% with every mint function getMintPrice() public view returns (uint256) { return (price * 1005) / 1000; } event SpiralMinted(uint256, bytes32); function _mintSpiral(bytes32 seed) internal { require(started, "NotStarted"); require(block.timestamp < (lastMintTime + MINT_EXPIRY_TIME), "MintsFinished"); uint256 nextMintPrice = getMintPrice(); require(msg.value >= nextMintPrice, "NotEnoughETH"); // Keep track of the total reward money totalReward += nextMintPrice; uint256 excessETH = 0; if (msg.value > nextMintPrice) { excessETH = msg.value - nextMintPrice; } // Increase the mint price price = nextMintPrice; // Increment TokenId uint256 tokenId = _tokenIdCounter; _tokenIdCounter += 1; // Save the seed for the RNG spiralSeeds[tokenId] = seed; // Set the last mint time. lastMintTime = block.timestamp; // Send any excess money back (bool success, ) = msg.sender.call{value: excessETH}(""); require(success, "Transfer failed."); // And actually mint _safeMint(msg.sender, tokenId); emit SpiralMinted(tokenId, seed); } // Mint a spiral based on a RandomWalkNFT function mintSpiralWithRWNFT(uint256 _rwnftTokenId) external payable nonReentrant { require(!mintedRWs[_rwnftTokenId], "Minted"); require(_rwNFT.ownerOf(_rwnftTokenId) == msg.sender, "DoesntOwnToken"); // Mark this RandomWalkNFT as already minted. mintedRWs[_rwnftTokenId] = true; // Record the mint price uint256 mintPrice = getMintPrice(); // Since we're minting based on RW, use the same seed _mintSpiral(_rwNFT.seeds(_rwnftTokenId)); // The equivalent of 33% of the ETH is used to mint IMPISH tokens. _impishDAO.deposit{value: (mintPrice * 33) / 100}(); // And send the impish tokens to the caller. _impishDAO.transfer(msg.sender, _impishDAO.balanceOf(address(this))); } // Mint a random Spiral function mintSpiralRandom() external payable nonReentrant { entropy = keccak256(abi.encode(block.timestamp, blockhash(block.number), msg.sender, price, entropy)); _mintSpiral(entropy); } // Claim winnings function claimWin(uint256 tokenId) external nonReentrant { require(started, "NotStarted"); require(block.timestamp > (lastMintTime + MINT_EXPIRY_TIME), "StillOpen"); require(tokenId < _tokenIdCounter, "OutofRange"); require(!winningsClaimed[tokenId], "Claimed"); // Make sure that this tokenId has actually won uint256 winningTokensAreGTE = 0; if (_tokenIdCounter > 10) { winningTokensAreGTE = _tokenIdCounter - 10; } require(tokenId >= winningTokensAreGTE, "DidnotWin"); // 1st place wins 10%, 2nd place 9%.... 10th place wins 1% uint256 winningPercent = tokenId - winningTokensAreGTE + 1; uint256 winnings = (totalReward * winningPercent) / 100; // Mark winnings as claimed winningsClaimed[tokenId] = true; // Send the winnings to owner of the TokenID (Not the minter) address winnerAddress = ownerOf(tokenId); // Transfer winnings (bool success, ) = winnerAddress.call{value: winnings}(""); require(success, "Transfer failed."); } function afterAllWinnings() external onlyOwner nonReentrant { require(started, "Started"); require(address(this).balance > 0, "Empty"); require(block.timestamp > (lastMintTime + MINT_EXPIRY_TIME), "StillOpen"); uint256 winningTokensAreGTE = 0; if (_tokenIdCounter > 10) { winningTokensAreGTE = _tokenIdCounter - 10; } uint256 tid; for (tid = winningTokensAreGTE; tid < _tokenIdCounter; tid++) { require(winningsClaimed[tid], "NotYetClaimed"); } // Transfer winnings (bool success, ) = owner().call{value: address(this).balance}(""); require(success, "TfrFailed"); } // Returns a list of token Ids owned by _owner. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } uint256[] memory result = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { result[i] = tokenOfOwnerByIndex(_owner, i); } return result; } // Set the lengths for the spirals function setSpiralLengths(uint256[] calldata tokenIDs, uint256[] calldata lengths) external onlyOwner { require(tokenIDs.length == lengths.length, "BadCall"); // Set the lengths for (uint256 i = 0; i < tokenIDs.length; i++) { spiralLengths[tokenIDs[i]] = lengths[i]; } } function setSpiralBitsContract(address _bitsContract) external onlyOwner { require(spiralBitsContract == address(0), "AlreadySet"); spiralBitsContract = _bitsContract; } // Increase length of a spiral function removeLengthFromSpiral(uint256 tokenId, uint256 trimLength) external { require(msg.sender == spiralBitsContract, "YouCantCall"); require(spiralLengths[tokenId] > 0, "NoTokenID"); // Solidity 0.8.0 does the underflow check here automatically require(spiralLengths[tokenId] - trimLength > 400000, "CantTrim"); spiralLengths[tokenId] = spiralLengths[tokenId] - trimLength; } // Decrease length of a spiral function addLengthToSpiral(uint256 tokenId, uint256 addLength) external { require(msg.sender == spiralBitsContract, "CantCall"); require(spiralLengths[tokenId] > 0, "NoID"); // Solidity 0.8.0 does the overflow check here automatically require(spiralLengths[tokenId] + addLength < 10000000, "CantAdd"); spiralLengths[tokenId] = spiralLengths[tokenId] + addLength; } // The following functions are overrides required by Solidity. function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } }
Decrease length of a spiral Solidity 0.8.0 does the overflow check here automatically
function addLengthToSpiral(uint256 tokenId, uint256 addLength) external { require(msg.sender == spiralBitsContract, "CantCall"); require(spiralLengths[tokenId] > 0, "NoID"); require(spiralLengths[tokenId] + addLength < 10000000, "CantAdd"); spiralLengths[tokenId] = spiralLengths[tokenId] + addLength; }
1,006,495
./partial_match/42/0x1550D3ac7dc80d1aE1a87eC2b85e08f9FdBb3EcA/sources/Locks.sol
Extend Rent Time if Box is known : function override
function extendRentTime(string memory boxId) private{ Box storage box = boxes[boxId]; if(box.owner == msg.sender){ uint time = coutRentTime(msg.value); if(time > 0) box.timePeriod = box.timePeriod + time; else{ revert("Ammount is to low"); } } else revert("Not Owner Interaction"); if(box.owner == msg.sender){ uint time = coutRentTime(msg.value); if(time > 0) box.timePeriod = box.timePeriod + time; else{ revert("Ammount is to low"); } } else revert("Not Owner Interaction"); }
9,069,963
./full_match/80001/0x2f40a1f04be1a7d87e3651AD23F62B97B14D9C57/sources/contracts/Polyverse.sol
"0+3+Hooray! ", msg.sender, " sent ", token amount, " PUSH to you!" We are passing identity here: https:docs.epns.io/developers/developer-guides/sending-notifications/advanced/notification-payload-types/identity/payload-identity-implementations
function purchaseTicket(uint256 eventId) public payable { Event storage eventDetails = _events[eventId]; require(msg.value >= eventDetails.ticketPrice, "Not enough amount"); require( eventDetails.participants.length < eventDetails.maxParticipants, "Full event" ); require(block.timestamp <= eventDetails.deadline, "Event over"); IERC20(tokenAddress).approve(msg.sender, eventDetails.ticketPrice); IERC20(tokenAddress).transfer(eventDetails.owner, msg.value); PolyverseEventNFT nftContract = PolyverseEventNFT( eventDetails.eventNFT ); _ticketIds.increment(); uint256 ticketNFTId = nftContract.mintTicket(msg.sender); _userToTicketId[msg.sender] = _ticketIds.current(); Ticket storage newTicket = _tickets[_ticketIds.current()]; newTicket.owner = msg.sender; newTicket.eventId = eventId; newTicket.seatNumber = eventDetails.participants.length; newTicket.ticketNFTId = ticketNFTId; eventDetails.participants.push(msg.sender); allTickets.push(newTicket); uint256 amount = eventDetails.ticketPrice; IPUSHCommInterface(EPNS_COMM_ADDRESS).sendNotification( bytes( string( abi.encodePacked( ) ) ) ); emit TicketPurchased(eventId, msg.sender, ticketNFTId); }
5,586,619
./partial_match/1/0xf9539C6e9Cdd31D2c5eF02052dA2DdF9C1bee757/sources/src/core/vaults/BaseVault.sol
Deposits the `asset` from msg.sender added to `creditor`'s deposit _amount is the amount of primary asset to deposit _creditor is the address that can claim/withdraw deposited amount/ pulling all collaterals from msg.sender An approve() by the msg.sender is required for all collaterals beforehand
function depositFor(uint256 _amount, address _creditor) external nonReentrant { if (_creditor == address(0)) _creditor = msg.sender; uint256 currentRound = _depositFor(_amount, _creditor); uint256[] memory amounts = _transferAssets(_amount, address(this), currentRound); emit Deposited(_creditor, amounts, currentRound); }
15,544,335
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "ERC721Enumerable.sol"; import "SafeMath.sol"; import "Counters.sol"; import "Ownable.sol"; import "Pausable.sol"; import "BPC.sol"; import "BPCSenderRecipient.sol"; import "ExternalFuncs.sol"; contract BPCLottery is ERC721, ERC777SenderRecipientMock, Ownable, Pausable { //using ExternalFuncs for *; using Counters for Counters.Counter; using SafeMath for uint256; IERC777 private m_bpc; bool private m_bpc_is_set; modifier isTokenSet() { require(m_bpc_is_set, "ERC777 is not set"); _; } address private m_company_account; Counters.Counter private m_ticket_id; Counters.Counter private m_lottery_id; uint256 private m_ticket_price; bool private is_lottery_open; uint256 private constant m_duration = 7 days; struct Winner { uint256 ticket_id; address addr; bool isSet; } mapping(uint256 => uint256) private m_lottery_id_pot; mapping(uint256 => uint256) private m_lottery_id_expires_at; mapping(uint256 => bool) private m_lottery_id_paid; mapping(uint256 => Winner) private m_lottery_id_winner; event WinnerAnnounced( address winner, uint256 winner_id, uint256 lottery_id, uint256 prize_size ); event WinnerPaid(address winner, uint256 lottery_id, uint256 prize_size); constructor( string memory _name, string memory _symbol, uint256 _ticket_price, address _company_account ) ERC721(_name, _symbol) { m_company_account = _company_account; // ERC-777 receiver init // See https://forum.openzeppelin.com/t/simple-erc777-token-example/746 _erc1820.setInterfaceImplementer( address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this) ); m_ticket_price = _ticket_price != 0 ? _ticket_price : 5000000000000000000; // 5 * 10^18 m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add( m_duration ); m_lottery_id_paid[m_lottery_id.current()] = false; is_lottery_open = true; m_bpc_is_set = false; } function setERC777(address _bpc) public onlyOwner { require(_bpc != address(0), "BPC address cannot be 0"); require( !m_bpc_is_set, "You have already set BPC address, can't do it again" ); m_bpc = IERC777(_bpc); m_bpc_is_set = true; } function pause() public onlyOwner whenNotPaused { _pause(); } function unPause() public onlyOwner whenPaused { _unpause(); } //function paused() public view comes as a base class method of Pausable function setTicketPrice(uint256 new_ticket_price) public onlyOwner isTokenSet { require(new_ticket_price > 0, "Ticket price should be greater than 0"); m_ticket_price = new_ticket_price; } //when not paused function getTicketPrice() public view returns (uint256) { require(!paused(), "Lottery is paused, please come back later"); return m_ticket_price; } //when not paused function buyTicket(uint256 bpc_tokens_amount, address participant) public isTokenSet { require(!paused(), "Lottery is paused, please come back later"); require( m_bpc.isOperatorFor(msg.sender, participant), "You MUST be an operator for participant" ); require( bpc_tokens_amount.mod(m_ticket_price) == 0, "Tokens amount should be a multiple of a Ticket Price" ); require( m_bpc.balanceOf(participant) >= bpc_tokens_amount, "You should have enough of Tokens in your Wallet" ); m_bpc.operatorSend( participant, address(this), bpc_tokens_amount, bytes(""), bytes("") ); m_lottery_id_pot[m_lottery_id.current()] = m_lottery_id_pot[ m_lottery_id.current() ].add(bpc_tokens_amount); uint256 tickets_count = bpc_tokens_amount.div(m_ticket_price); for (uint256 i = 0; i != tickets_count; ++i) { m_ticket_id.increment(); _mint(participant, m_ticket_id.current()); } } //when not paused function getCurrentLotteryTicketsCount(address participant) public view returns (uint256) { require(!paused(), "Lottery is paused, please come back later"); require( m_bpc.isOperatorFor(msg.sender, participant), "You MUST be an operator for participant" ); return this.balanceOf(participant); } function getCurrentLotteryId() public view returns (uint256) { return m_lottery_id.current(); } function getCurrentLotteryPot() public view returns (uint256) { return m_lottery_id_pot[m_lottery_id.current()]; } function announceWinnerAndRevolve() public onlyOwner isTokenSet { require(isLotteryPeriodOver(), "The current lottery is still running"); forceAnnounceWinnerAndRevolve(); } function forceAnnounceWinnerAndRevolve() public onlyOwner isTokenSet { uint256 prize_size = m_lottery_id_pot[m_lottery_id.current()].div(2); uint256 id = m_lottery_id.current(); if (!m_lottery_id_winner[id].isSet) { m_lottery_id_winner[id] = setWinner(prize_size); } if (!isEmptyWinner(m_lottery_id_winner[id]) && !m_lottery_id_paid[id]) { splitPotWith(m_lottery_id_winner[id].addr, prize_size); m_lottery_id_paid[id] = true; m_lottery_id_pot[id] = 0; } if (!paused()) { revolveLottery(); } } function isLotteryPeriodOver() private view returns (bool) { return m_lottery_id_expires_at[m_lottery_id.current()] < block.timestamp; } function getWinner(uint256 id) public view returns (address) { require( m_lottery_id_winner[id].isSet, "Lottery Id Winner or Lottery Id not found" ); return m_lottery_id_winner[id].addr; } function setWinner(uint256 prize_size) private returns (Winner memory) { Winner memory winner; winner.isSet = true; if (m_ticket_id.current() != 0) { winner.ticket_id = prng().mod(m_ticket_id.current()).add(1); winner.addr = this.ownerOf(winner.ticket_id); emit WinnerAnnounced( winner.addr, winner.ticket_id, m_lottery_id.current(), prize_size ); } else { winner.ticket_id = 0; winner.addr = address(0); } return winner; } function isEmptyWinner(Winner memory winner) private pure returns (bool) { return winner.addr == address(0); } function splitPotWith(address winner_address, uint256 prize_size) private { m_bpc.operatorSend( address(this), winner_address, prize_size, bytes(""), bytes("") ); m_bpc.operatorSend( address(this), m_company_account, prize_size, bytes(""), bytes("") ); emit WinnerPaid(winner_address, m_lottery_id.current(), prize_size); } function revolveLottery() private { uint256 size = m_ticket_id.current(); if (size != 0) { for (uint256 i = 1; i <= size; ++i) { _burn(i); } } m_ticket_id.reset(); m_lottery_id.increment(); m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add( m_duration ); } function prng() private view returns (uint256) { return uint256( keccak256( abi.encodePacked( block.difficulty, block.timestamp, m_ticket_id.current() ) ) ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "ERC721.sol"; import "IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (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 (access/Ownable.sol) pragma solidity ^0.8.0; import "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 (security/Pausable.sol) pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "ERC777.sol"; import "AccessControl.sol"; import "SafeMath.sol"; import "ReentrancyGuard.sol"; contract BPC is ERC777, AccessControl, ReentrancyGuard { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 private constant m_tokens_per_eth = 100; address private m_company_account; uint256 private m_entry_fee; uint256 private m_exit_fee; uint256 private m_max_supply; constructor( string memory _name, string memory _symbol, address[] memory _default_operators, uint256 _max_supply, uint256 _initial_supply, uint256 _entry_fee, uint256 _exit_fee, address _managing_account, address _company_account ) ERC777(_name, _symbol, _default_operators) { _grantRole(DEFAULT_ADMIN_ROLE, _managing_account); _grantRole(MINTER_ROLE, _company_account); m_max_supply = _max_supply; _mint(_company_account, _initial_supply, "", "", false); m_company_account = _company_account; m_entry_fee = _entry_fee; m_exit_fee = _exit_fee; } function mint(uint256 amount) public onlyRole(MINTER_ROLE) { require( totalSupply().add(amount) <= m_max_supply, "Amount that is about to be minted reaches the Max Supply" ); _mint(msg.sender, amount, bytes(""), bytes(""), false); } //burn and operatorBurn of ERC777 make all required checks and update _totalSupply that holds current Tokens qty //no need to override those funcs function fromEtherToTokens() public payable { uint256 tokens_to_buy = msg.value * m_tokens_per_eth; uint256 company_token_balance = this.balanceOf(m_company_account); require( tokens_to_buy > 0, "You need to send some more ether, what you provide is not enough for transaction" ); require( tokens_to_buy <= company_token_balance, "Not enough tokens in the reserve" ); uint256 updated_value = getEntryFeeValue(tokens_to_buy); _send( m_company_account, msg.sender, updated_value, bytes(""), bytes(""), false ); } function fromTokensToEther(uint256 tokens_to_sell) public nonReentrant { require(tokens_to_sell > 0, "You need to sell at least some tokens"); // Check that the user's token balance is enough to do the swap uint256 user_token_balance = this.balanceOf(msg.sender); require( user_token_balance >= tokens_to_sell, "Your balance is lower than the amount of tokens you want to sell" ); uint256 updated_value = getExitFeeValue(tokens_to_sell); uint256 eth_to_transfer = updated_value / m_tokens_per_eth; uint256 company_eth_balance = address(this).balance; require( company_eth_balance >= eth_to_transfer, "BPC Owner doesn't have enough funds to accept this sell request" ); _send( msg.sender, m_company_account, tokens_to_sell, bytes(""), bytes(""), false ); payable(msg.sender).transfer(eth_to_transfer); } function getTokenPrice() public view returns (uint256) { return m_tokens_per_eth; } function getEntryFee() public view returns (uint256) { return m_entry_fee; } function getExitFee() public view returns (uint256) { return m_exit_fee; } function setEntryFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) { require( fee >= 0 && fee <= 100, "Fee must be an integer percentage, ie 42" ); m_entry_fee = fee; } function setExitFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) { require( fee >= 0 && fee <= 100, "Fee must be an integer percentage, ie 42" ); m_exit_fee = fee; } function getEntryFeeValue(uint256 value) private view returns (uint256) { if (m_entry_fee != 0) { uint256 fee_value = (m_entry_fee * value) / 100; uint256 updated_value = value - fee_value; return updated_value; } else { return value; } } function getExitFeeValue(uint256 value) private view returns (uint256) { if (m_exit_fee != 0) { uint256 fee_value = (m_exit_fee * value) / 100; uint256 updated_value = value - fee_value; return updated_value; } else { return value; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/ERC777.sol) pragma solidity ^0.8.0; import "IERC777.sol"; import "IERC777Recipient.sol"; import "IERC777Sender.sol"; import "IERC20.sol"; import "Address.sol"; import "Context.sol"; import "IERC1820Registry.sol"; /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using Address for address; IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < defaultOperators_.length; i++) { _defaultOperators[defaultOperators_[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure virtual returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn( address account, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); uint256 currentAllowance = _allowances[holder][spender]; require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance"); _approve(holder, spender, currentAllowance - amount); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { _mint(account, amount, userData, operatorData, true); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If `requireReceptionAck` is set to true, and if a send hook is * registered for `account`, the corresponding function will be called with * `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply += amount; _balances[account] += amount; _callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: burn amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _totalSupply -= amount; emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve( address holder, address spender, uint256 value ) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `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 operator, address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send( address recipient, uint256 amount, bytes calldata data ) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Sender.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // 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 (utils/introspection/IERC1820Registry.sol) pragma solidity ^0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer( address account, bytes32 _interfaceHash, address implementer ) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "IAccessControl.sol"; import "Context.sol"; import "Strings.sol"; import "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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC777.sol"; import "IERC777Sender.sol"; import "IERC777Recipient.sol"; import "Context.sol"; import "IERC1820Registry.sol"; import "ERC1820Implementer.sol"; contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer { event TokensToSendCalled( address operator, address from, address to, uint256 amount, bytes data, bytes operatorData, address token, uint256 fromBalance, uint256 toBalance ); event TokensReceivedCalled( address operator, address from, address to, uint256 amount, bytes data, bytes operatorData, address token, uint256 fromBalance, uint256 toBalance ); // Emitted in ERC777Mock. Here for easier decoding event BeforeTokenTransfer(); bool private _shouldRevertSend; bool private _shouldRevertReceive; IERC1820Registry public _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 public constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 public constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override { if (_shouldRevertSend) { revert(); } IERC777 token = IERC777(_msgSender()); uint256 fromBalance = token.balanceOf(from); // when called due to burn, to will be the zero address, which will have a balance of 0 uint256 toBalance = token.balanceOf(to); emit TokensToSendCalled( operator, from, to, amount, userData, operatorData, address(token), fromBalance, toBalance ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override { if (_shouldRevertReceive) { revert(); } IERC777 token = IERC777(_msgSender()); uint256 fromBalance = token.balanceOf(from); // when called due to burn, to will be the zero address, which will have a balance of 0 uint256 toBalance = token.balanceOf(to); emit TokensReceivedCalled( operator, from, to, amount, userData, operatorData, address(token), fromBalance, toBalance ); } function senderFor(address account) public { _registerInterfaceForAddress(_TOKENS_SENDER_INTERFACE_HASH, account); address self = address(this); if (account == self) { registerSender(self); } } function registerSender(address sender) public { _erc1820.setInterfaceImplementer(address(this), _TOKENS_SENDER_INTERFACE_HASH, sender); } function recipientFor(address account) public { _registerInterfaceForAddress(_TOKENS_RECIPIENT_INTERFACE_HASH, account); address self = address(this); if (account == self) { registerRecipient(self); } } function registerRecipient(address recipient) public { _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient); } function setShouldRevertSend(bool shouldRevert) public { _shouldRevertSend = shouldRevert; } function setShouldRevertReceive(bool shouldRevert) public { _shouldRevertReceive = shouldRevert; } function send( IERC777 token, address to, uint256 amount, bytes memory data ) public { // This is 777's send function, not the Solidity send function token.send(to, amount, data); // solhint-disable-line check-send-result } function burn( IERC777 token, uint256 amount, bytes memory data ) public { token.burn(amount, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC1820Implementer.sol) pragma solidity ^0.8.0; import "IERC1820Implementer.sol"; /** * @dev Implementation of the {IERC1820Implementer} interface. * * Contracts may inherit from this and call {_registerInterfaceForAddress} to * declare their willingness to be implementers. * {IERC1820Registry-setInterfaceImplementer} should then be called for the * registration to be complete. */ contract ERC1820Implementer is IERC1820Implementer { bytes32 private constant _ERC1820_ACCEPT_MAGIC = keccak256("ERC1820_ACCEPT_MAGIC"); mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces; /** * @dev See {IERC1820Implementer-canImplementInterfaceForAddress}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view virtual override returns (bytes32) { return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00); } /** * @dev Declares the contract as willing to be an implementer of * `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer} and * {IERC1820Registry-interfaceHash}. */ function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual { _supportedInterfaces[interfaceHash][account] = true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol) pragma solidity ^0.8.0; /** * @dev Interface for an ERC1820 implementer, as defined in the * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. * Used by contracts that will be registered as implementers in the * {IERC1820Registry}. */ interface IERC1820Implementer { /** * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract * implements `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ABDKMath64x64.sol"; import "Strings.sol"; library ExternalFuncs { // from here https://medium.com/coinmonks/math-in-solidity-part-4-compound-interest-512d9e13041b /* function pow (int128 x, uint n) public pure returns (int128 r) { r = ABDKMath64x64.fromUInt (1); while (n > 0) { if (n % 2 == 1) { r = ABDKMath64x64.mul (r, x); n -= 1; } else { x = ABDKMath64x64.mul (x, x); n /= 2; } } } */ function compound( uint256 principal, uint256 ratio, uint256 n ) public pure returns (uint256) { return ABDKMath64x64.mulu( ABDKMath64x64.pow( //pow - original code ABDKMath64x64.add( ABDKMath64x64.fromUInt(1), ABDKMath64x64.divu(ratio, 10**4) ), //(1+r), where r is allowed to be one hundredth of a percent, ie 5/100/100 n ), //(1+r)^n principal ); //A_0 * (1+r)^n } function Today() public view returns (uint256) { return block.timestamp / 1 days; } function isStakeSizeOk(uint256 amount, uint256 decimals) public pure returns (bool) { return amount == 1000 * 10**decimals || amount == 3000 * 10**decimals || amount == 5000 * 10**decimals || amount == 10000 * 10**decimals || amount == 20000 * 10**decimals || amount == 50000 * 10**decimals || amount == 100000 * 10**decimals || amount == 250000 * 10**decimals || amount >= 1000000 * 10**decimals; } function getErrorMsg(string memory text, uint256 value) public pure returns (string memory) { string memory _msg = string( abi.encodePacked(text, Strings.toString(value)) ); return _msg; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { unchecked { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { unchecked { return int64(x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { unchecked { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(int256(x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { unchecked { require(x >= 0); return uint64(uint128(x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128(int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128(int128 x) internal pure returns (int256) { unchecked { return int256(x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli(int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require( y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000 ); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu(x, uint256(y)); if (negativeResult) { require( absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000 ); return -int256(absoluteResult); // We rely on overflow behavior here } else { require( absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); return int256(absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(int256(x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(int256(x)) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div(int128 x, int128 y) internal pure returns (int128) { unchecked { require(y != 0); int256 result = (int256(x) << 64) / y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi(int256 x, int256 y) internal pure returns (int128) { unchecked { require(y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu(uint256(x), uint256(y)); if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { unchecked { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg(int128 x) internal pure returns (int128) { unchecked { require(x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs(int128 x) internal pure returns (int128) { unchecked { require(x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { unchecked { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg(int128 x, int128 y) internal pure returns (int128) { unchecked { return int128((int256(x) + int256(y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg(int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256(x) * int256(y); require(m >= 0); require( m < 0x4000000000000000000000000000000000000000000000000000000000000000 ); return int128(sqrtu(uint256(m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128(x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x2 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x4 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x8 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require(absXShift < 64); if (y & 0x1 != 0) { absResult = (absResult * absX) >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = (absX * absX) >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require(resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256(absResult) : int256(absResult); require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt(int128 x) internal pure returns (int128) { unchecked { require(x >= 0); return int128(sqrtu(uint256(int256(x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { unchecked { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(int256(x)) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { unchecked { require(x > 0); return int128( int256( (uint256(int256(log_2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128 ) ); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2(int128 x) internal pure returns (int128) { unchecked { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128; if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128; if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128; if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128; if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128; if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128; if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128; if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128; if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128; if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128; if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128; if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128; if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128; if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128; if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128; if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128; if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128; if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128; if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128; if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128; if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128; if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128; if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128; if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128; if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128; if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128; if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128; if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128; if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128; if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128; if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128; if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128; if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128; if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128; if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128; if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128; if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128; if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128; if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128; if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128; if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128; if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128; if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128; if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128; if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128; if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128; if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128; if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128; if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128; if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128; if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128; if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128; result >>= uint256(int256(63 - (x >> 64))); require(result <= uint256(int256(MAX_64x64))); return int128(int256(result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp(int128 x) internal pure returns (int128) { unchecked { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2( int128( (int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128 ) ); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) private pure returns (uint128) { unchecked { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } }
Convert signed 64.64 fixed point number into signed 128.128 fixed point number. x signed 64.64-bit fixed point number return signed 128.128 fixed point number/
function to128x128(int128 x) internal pure returns (int256) { unchecked { return int256(x) << 64; } }
154,138
./partial_match/1/0xA472FcA97F969F656EC6928578106be7936CBD10/sources/contracts/MultiplierProxy.sol
setter to set the position of an implementation from the implementation position onwards
function _setImplementation(address _newImplementation) internal { require(msg.sender == proxyOwner()); bytes32 position = implementationPosition; assembly { sstore(position, _newImplementation) } }
9,177,791
./partial_match/1/0x80D186B4C786Ea66592b2c52e2004AB10CfE4CF3/sources/Lynx.sol
Set an Address as LP _lpAddress Address to set as LP _isLpAddress enable or disable address as an LP/
function setLpAddress( address _lpAddress, bool _isLpAddress ) external onlyOwner { isLpAddress[_lpAddress] = _isLpAddress; isDividendExempt[_lpAddress] = _isLpAddress; emit SetAddressAsLp(_lpAddress, _isLpAddress); }
2,861,743
./full_match/80001/0x6D1C8963dac5a0Fb42bbCb709cAe14dab9A3b5D8/sources/StakeManager2.sol
@inheritdoc IStakeManager/
function unstakeV2( address validator, Token.Type token, uint256 amount ) external validatorExists(validator) stakerExists(msg.sender) onlyNotLastBlock { Staker storage _staker = stakers[msg.sender]; amount = _staker.unstake(environment, validators[validator], token, amount); if (amount == 0) revert NoAmount(); _staker.lockedUnstakes.push(LockedUnstake(token, amount, block.timestamp + 10 days)); stakeUpdates.sub(stakeAmounts, environment.epoch() + 1, amount); if (address(candidateManager) != address(0)) { candidateManager.afterStakeUpdate(validator); } emit UnstakedV2(msg.sender, validator, _staker.lockedUnstakes.length - 1); }
860,713
./partial_match/42/0x8cDBd716d307eAaDdbc808A67bdaD90602C82978/sources/PaymentGateway.sol
Sender account claim the amount from the escorw when the payment expires senderId The sender unique ID generated by EPN destinationId The destination unique ID generated by EPN/
function refundEthAmount(uint256 senderId, uint256 destinationId) public { require (senderId != 0 && senderId != destinationId); require(epnToken.isRegistered(senderId) && epnToken.getOwnerOf(senderId) == msg.sender); uint256 mappingId = getUniqueId(senderId, destinationId); EscrowPayment storage payment = escrowEthPayments[mappingId]; require(payment.senderId == senderId && payment.amount > 0 && payment.expiryTime < block.timestamp); address payable senderAddress = payable(epnToken.getOwnerOf(senderId)); uint256 refundAmount = payment.amount; payment.amount = 0; senderAddress.transfer(refundAmount); emit RefundEthTransfered(mappingId, senderId, destinationId, refundAmount); }
3,377,680
pragma solidity ^0.4.11; import './IProposal.sol'; import './Owned.sol'; /** A Proposal interface involving approval by one or more members. */ contract IMemberProposal is IProposal, Owned { mapping(address => bool) approvals; /** Returns whether the given member has approved the proposal. */ function isApprovedByMember(address member) public constant returns(bool) { return approvals[member]; } /** Approves the proposal by the sender. */ function approve() public { approvals[msg.sender] = true; } /** The owner can force approval by a member. */ /** Owner refers to the contract creator which will be the prism contract */ function approveAsMember(address member) public onlyowner { approvals[member] = true; } // ABSTRACT function isApproved() public constant returns(bool); }
Approves the proposal by the sender. /
function approve() public { approvals[msg.sender] = true; }
12,720,111
pragma solidity ^0.5.10; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a, "Add error"); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a, "Sub error"); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "Mul error"); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0, "Div error"); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20 { function totalSupply() external returns (uint); function balanceOf(address tokenOwner) external returns (uint balance); function allowance(address tokenOwner, address spender) external returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external 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); constructor() public { owner = msg.sender; } modifier onlyOwner { require(tx.origin == owner); //inject USING TX ORIGIN FOR AUTHENTICATION _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // Airdropper contract // ---------------------------------------------------------------------------- contract Airdropper is Owned { using SafeMath for uint; ERC20 public token; /** * @dev Constructor. * @param tokenAddress Address of the token contract. */ constructor(address tokenAddress) public { token = ERC20(tokenAddress); } /** * @dev Airdrop. * @ !important Before using, send needed token amount to this contract */ function airdrop(address[] memory dests, uint[] memory values) public onlyOwner { // This simple validation will catch most mistakes without consuming // too much gas. require(dests.length == values.length); for (uint256 i = 0; i < dests.length; i++) { token.transfer(dests[i], values[i]); } } /** * @dev Return all tokens back to owner, in case any were accidentally * transferred to this contract. */ function returnTokens() public onlyOwner { token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Destroy this contract and recover any ether to the owner. */ function destroy() public onlyOwner { selfdestruct(msg.sender); } }
Destroy this contract and recover any ether to the owner./
function destroy() public onlyOwner { selfdestruct(msg.sender); }
882,543
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". This adds two-phase * ownership control to OpenZeppelin's Ownable class. In this model, the original owner * designates a new owner but does not actually transfer ownership. The new owner then accepts * ownership and completes the transfer. */ contract Ownable { address public owner; address public pendingOwner; 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; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @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)); pendingOwner = _newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title CarbonDollarStorage * @notice Contains necessary storage contracts for CarbonDollar (FeeSheet and StablecoinWhitelist). */ contract CarbonDollarStorage is Ownable { using SafeMath for uint256; /** Mappings */ /* fees for withdrawing to stablecoin, in tenths of a percent) */ mapping (address => uint256) public fees; /** @dev Units for fees are always in a tenth of a percent */ uint256 public defaultFee; /* is the token address referring to a stablecoin/whitelisted token? */ mapping (address => bool) public whitelist; /** Events */ event DefaultFeeChanged(uint256 oldFee, uint256 newFee); event FeeChanged(address indexed stablecoin, uint256 oldFee, uint256 newFee); event FeeRemoved(address indexed stablecoin, uint256 oldFee); event StablecoinAdded(address indexed stablecoin); event StablecoinRemoved(address indexed stablecoin); /** @notice Sets the default fee for burning CarbonDollar into a whitelisted stablecoin. @param _fee The default fee. */ function setDefaultFee(uint256 _fee) public onlyOwner { uint256 oldFee = defaultFee; defaultFee = _fee; if (oldFee != defaultFee) emit DefaultFeeChanged(oldFee, _fee); } /** @notice Set a fee for burning CarbonDollar into a stablecoin. @param _stablecoin Address of a whitelisted stablecoin. @param _fee the fee. */ function setFee(address _stablecoin, uint256 _fee) public onlyOwner { uint256 oldFee = fees[_stablecoin]; fees[_stablecoin] = _fee; if (oldFee != _fee) emit FeeChanged(_stablecoin, oldFee, _fee); } /** @notice Remove the fee for burning CarbonDollar into a particular kind of stablecoin. @param _stablecoin Address of stablecoin. */ function removeFee(address _stablecoin) public onlyOwner { uint256 oldFee = fees[_stablecoin]; fees[_stablecoin] = 0; if (oldFee != 0) emit FeeRemoved(_stablecoin, oldFee); } /** @notice Add a token to the whitelist. @param _stablecoin Address of the new stablecoin. */ function addStablecoin(address _stablecoin) public onlyOwner { whitelist[_stablecoin] = true; emit StablecoinAdded(_stablecoin); } /** @notice Removes a token from the whitelist. @param _stablecoin Address of the ex-stablecoin. */ function removeStablecoin(address _stablecoin) public onlyOwner { whitelist[_stablecoin] = false; emit StablecoinRemoved(_stablecoin); } /** * @notice Compute the fee that will be charged on a "burn" operation. * @param _amount The amount that will be traded. * @param _stablecoin The stablecoin whose fee will be used. */ function computeStablecoinFee(uint256 _amount, address _stablecoin) public view returns (uint256) { uint256 fee = fees[_stablecoin]; return computeFee(_amount, fee); } /** * @notice Compute the fee that will be charged on a "burn" operation. * @param _amount The amount that will be traded. * @param _fee The fee that will be charged, in tenths of a percent. */ function computeFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return _amount.mul(_fee).div(1000); } } /** * 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; } } /** * @title PermissionedTokenStorage * @notice a PermissionedTokenStorage is constructed by setting Regulator, BalanceSheet, and AllowanceSheet locations. * Once the storages are set, they cannot be changed. */ contract PermissionedTokenStorage is Ownable { using SafeMath for uint256; /** Storage */ mapping (address => mapping (address => uint256)) public allowances; mapping (address => uint256) public balances; uint256 public totalSupply; function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner { allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].add(_value); } function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner { allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].sub(_value); } function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner { allowances[_tokenHolder][_spender] = _value; } function addBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].add(_value); } function subBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = balances[_addr].sub(_value); } function setBalance(address _addr, uint256 _value) public onlyOwner { balances[_addr] = _value; } function addTotalSupply(uint256 _value) public onlyOwner { totalSupply = totalSupply.add(_value); } function subTotalSupply(uint256 _value) public onlyOwner { totalSupply = totalSupply.sub(_value); } function setTotalSupply(uint256 _value) public onlyOwner { totalSupply = _value; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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 Lockable * @dev Base contract which allows children to lock certain methods from being called by clients. * Locked methods are deemed unsafe by default, but must be implemented in children functionality to adhere by * some inherited standard, for example. */ contract Lockable is Ownable { // Events event Unlocked(); event Locked(); // Fields bool public isMethodEnabled = false; // Modifiers /** * @dev Modifier that disables functions by default unless they are explicitly enabled */ modifier whenUnlocked() { require(isMethodEnabled); _; } // Methods /** * @dev called by the owner to enable method */ function unlock() onlyOwner public { isMethodEnabled = true; emit Unlocked(); } /** * @dev called by the owner to disable method, back to normal state */ function lock() onlyOwner public { isMethodEnabled = false; emit Locked(); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. Identical to OpenZeppelin version * except that it uses local Ownable contract */ 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(); } } /** * * @dev Stores permissions and validators and provides setter and getter methods. * Permissions determine which methods users have access to call. Validators * are able to mutate permissions at the Regulator level. * */ contract RegulatorStorage is Ownable { /** Structs */ /* Contains metadata about a permission to execute a particular method signature. */ struct Permission { string name; // A one-word description for the permission. e.g. "canMint" string description; // A longer description for the permission. e.g. "Allows user to mint tokens." string contract_name; // e.g. "PermissionedToken" bool active; // Permissions can be turned on or off by regulator } /** Constants: stores method signatures. These are potential permissions that a user can have, and each permission gives the user the ability to call the associated PermissionedToken method signature */ bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)")); bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)")); bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)")); bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)")); bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()")); /** Mappings */ /* each method signature maps to a Permission */ mapping (bytes4 => Permission) public permissions; /* list of validators, either active or inactive */ mapping (address => bool) public validators; /* each user can be given access to a given method signature */ mapping (address => mapping (bytes4 => bool)) public userPermissions; /** Events */ event PermissionAdded(bytes4 methodsignature); event PermissionRemoved(bytes4 methodsignature); event ValidatorAdded(address indexed validator); event ValidatorRemoved(address indexed validator); /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** * @notice Sets a permission within the list of permissions. * @param _methodsignature Signature of the method that this permission controls. * @param _permissionName A "slug" name for this permission (e.g. "canMint"). * @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens"). * @param _contractName Name of the contract that the method belongs to. */ function addPermission( bytes4 _methodsignature, string _permissionName, string _permissionDescription, string _contractName) public onlyValidator { Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true); permissions[_methodsignature] = p; emit PermissionAdded(_methodsignature); } /** * @notice Removes a permission the list of permissions. * @param _methodsignature Signature of the method that this permission controls. */ function removePermission(bytes4 _methodsignature) public onlyValidator { permissions[_methodsignature].active = false; emit PermissionRemoved(_methodsignature); } /** * @notice Sets a permission in the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature"); userPermissions[_who][_methodsignature] = true; } /** * @notice Removes a permission from the list of permissions that a user has. * @param _methodsignature Signature of the method that this permission controls. */ function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator { require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature"); userPermissions[_who][_methodsignature] = false; } /** * @notice add a Validator * @param _validator Address of validator to add */ function addValidator(address _validator) public onlyOwner { validators[_validator] = true; emit ValidatorAdded(_validator); } /** * @notice remove a Validator * @param _validator Address of validator to remove */ function removeValidator(address _validator) public onlyOwner { validators[_validator] = false; emit ValidatorRemoved(_validator); } /** * @notice does validator exist? * @return true if yes, false if no **/ function isValidator(address _validator) public view returns (bool) { return validators[_validator]; } /** * @notice does permission exist? * @return true if yes, false if no **/ function isPermission(bytes4 _methodsignature) public view returns (bool) { return permissions[_methodsignature].active; } /** * @notice get Permission structure * @param _methodsignature request to retrieve the Permission struct for this methodsignature * @return Permission **/ function getPermission(bytes4 _methodsignature) public view returns (string name, string description, string contract_name, bool active) { return (permissions[_methodsignature].name, permissions[_methodsignature].description, permissions[_methodsignature].contract_name, permissions[_methodsignature].active); } /** * @notice does permission exist? * @return true if yes, false if no **/ function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) { return userPermissions[_who][_methodsignature]; } } /** * @title Regulator * @dev Regulator can be configured to meet relevant securities regulations, KYC policies * AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken * makes compliant transfers possible. Contains the userPermissions necessary * for regulatory compliance. * */ contract Regulator is RegulatorStorage { /** Modifiers */ /** * @notice Throws if called by any account that does not have access to set attributes */ modifier onlyValidator() { require (isValidator(msg.sender), "Sender must be validator"); _; } /** Events */ event LogBlacklistedUser(address indexed who); event LogRemovedBlacklistedUser(address indexed who); event LogSetMinter(address indexed who); event LogRemovedMinter(address indexed who); event LogSetBlacklistDestroyer(address indexed who); event LogRemovedBlacklistDestroyer(address indexed who); event LogSetBlacklistSpender(address indexed who); event LogRemovedBlacklistSpender(address indexed who); /** * @notice Sets the necessary permissions for a user to mint tokens. * @param _who The address of the account that we are setting permissions for. */ function setMinter(address _who) public onlyValidator { _setMinter(_who); } /** * @notice Removes the necessary permissions for a user to mint tokens. * @param _who The address of the account that we are removing permissions for. */ function removeMinter(address _who) public onlyValidator { _removeMinter(_who); } /** * @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account. * @param _who The address of the account that we are setting permissions for. */ function setBlacklistSpender(address _who) public onlyValidator { require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token"); setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG); emit LogSetBlacklistSpender(_who); } /** * @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account. * @param _who The address of the account that we are removing permissions for. */ function removeBlacklistSpender(address _who) public onlyValidator { require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token"); removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG); emit LogRemovedBlacklistSpender(_who); } /** * @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account. * @param _who The address of the account that we are setting permissions for. */ function setBlacklistDestroyer(address _who) public onlyValidator { require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token"); setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); emit LogSetBlacklistDestroyer(_who); } /** * @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account. * @param _who The address of the account that we are removing permissions for. */ function removeBlacklistDestroyer(address _who) public onlyValidator { require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token"); removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); emit LogRemovedBlacklistDestroyer(_who); } /** * @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts * frozen; they cannot transfer, burn, or withdraw any tokens. * @param _who The address of the account that we are setting permissions for. */ function setBlacklistedUser(address _who) public onlyValidator { _setBlacklistedUser(_who); } /** * @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts * frozen; they cannot transfer, burn, or withdraw any tokens. * @param _who The address of the account that we are changing permissions for. */ function removeBlacklistedUser(address _who) public onlyValidator { _removeBlacklistedUser(_who); } /** Returns whether or not a user is blacklisted. * @param _who The address of the account in question. * @return `true` if the user is blacklisted, `false` otherwise. */ function isBlacklistedUser(address _who) public view returns (bool) { return (hasUserPermission(_who, BLACKLISTED_SIG)); } /** Returns whether or not a user is a blacklist spender. * @param _who The address of the account in question. * @return `true` if the user is a blacklist spender, `false` otherwise. */ function isBlacklistSpender(address _who) public view returns (bool) { return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG); } /** Returns whether or not a user is a blacklist destroyer. * @param _who The address of the account in question. * @return `true` if the user is a blacklist destroyer, `false` otherwise. */ function isBlacklistDestroyer(address _who) public view returns (bool) { return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); } /** Returns whether or not a user is a minter. * @param _who The address of the account in question. * @return `true` if the user is a minter, `false` otherwise. */ function isMinter(address _who) public view returns (bool) { return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG)); } /** Internal Functions **/ function _setMinter(address _who) internal { require(isPermission(MINT_SIG), "Minting not supported by token"); require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token"); setUserPermission(_who, MINT_SIG); setUserPermission(_who, MINT_CUSD_SIG); emit LogSetMinter(_who); } function _removeMinter(address _who) internal { require(isPermission(MINT_SIG), "Minting not supported by token"); require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token"); removeUserPermission(_who, MINT_CUSD_SIG); removeUserPermission(_who, MINT_SIG); emit LogRemovedMinter(_who); } function _setBlacklistedUser(address _who) internal { require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token"); setUserPermission(_who, BLACKLISTED_SIG); emit LogBlacklistedUser(_who); } function _removeBlacklistedUser(address _who) internal { require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token"); removeUserPermission(_who, BLACKLISTED_SIG); emit LogRemovedBlacklistedUser(_who); } } /** * @title PermissionedToken * @notice A permissioned token that enables transfers, withdrawals, and deposits to occur * if and only if it is approved by an on-chain Regulator service. PermissionedToken is an * ERC-20 smart contract representing ownership of securities and overrides the * transfer, burn, and mint methods to check with the Regulator. */ contract PermissionedToken is ERC20, Pausable, Lockable { using SafeMath for uint256; /** Events */ event DestroyedBlacklistedTokens(address indexed account, uint256 amount); event ApprovedBlacklistedAddressSpender(address indexed owner, address indexed spender, uint256 value); event Mint(address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event ChangedRegulator(address indexed oldRegulator, address indexed newRegulator ); PermissionedTokenStorage public tokenStorage; Regulator public regulator; /** * @dev create a new PermissionedToken with a brand new data storage **/ constructor (address _regulator) public { regulator = Regulator(_regulator); tokenStorage = new PermissionedTokenStorage(); } /** Modifiers **/ /** @notice Modifier that allows function access to be restricted based on * whether the regulator allows the message sender to execute that function. **/ modifier requiresPermission() { require (regulator.hasUserPermission(msg.sender, msg.sig), "User does not have permission to execute function"); _; } /** @notice Modifier that checks whether or not a transferFrom operation can * succeed with the given _from and _to address. See transferFrom()'s documentation for * more details. **/ modifier transferFromConditionsRequired(address _from, address _to) { require(!regulator.isBlacklistedUser(_to), "Recipient cannot be blacklisted"); // If the origin user is blacklisted, the transaction can only succeed if // the message sender is a user that has been approved to transfer // blacklisted tokens out of this address. bool is_origin_blacklisted = regulator.isBlacklistedUser(_from); // Is the message sender a person with the ability to transfer tokens out of a blacklisted account? bool sender_can_spend_from_blacklisted_address = regulator.isBlacklistSpender(msg.sender); require(!is_origin_blacklisted || sender_can_spend_from_blacklisted_address, "Origin cannot be blacklisted if spender is not an approved blacklist spender"); _; } /** @notice Modifier that checks whether a user is blacklisted. * @param _user The address of the user to check. **/ modifier userBlacklisted(address _user) { require(regulator.isBlacklistedUser(_user), "User must be blacklisted"); _; } /** @notice Modifier that checks whether a user is not blacklisted. * @param _user The address of the user to check. **/ modifier userNotBlacklisted(address _user) { require(!regulator.isBlacklistedUser(_user), "User must not be blacklisted"); _; } /** Functions **/ /** * @notice Allows user to mint if they have the appropriate permissions. User generally * must have minting authority. * @dev Should be access-restricted with the 'requiresPermission' modifier when implementing. * @param _to The address of the receiver * @param _amount The number of tokens to mint */ function mint(address _to, uint256 _amount) public userNotBlacklisted(_to) requiresPermission whenNotPaused { _mint(_to, _amount); } /** * @notice Remove CUSD from supply * @param _amount The number of tokens to burn * @return `true` if successful and `false` if unsuccessful */ function burn(uint256 _amount) userNotBlacklisted(msg.sender) public whenNotPaused { _burn(msg.sender, _amount); } /** * @notice Implements ERC-20 standard approve function. Locked or disabled by default to protect against * double spend attacks. To modify allowances, clients should call safer increase/decreaseApproval methods. * Upon construction, all calls to approve() will revert unless this contract owner explicitly unlocks approve() */ function approve(address _spender, uint256 _value) public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused whenUnlocked returns (bool) { tokenStorage.setAllowance(msg.sender, _spender, _value); emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * @notice increaseApproval should be used instead of approve when the user's allowance * is greater than 0. Using increaseApproval protects against potential double-spend attacks * by moving the check of whether the user has spent their allowance to the time that the transaction * is mined, removing the user's ability to double-spend * @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 userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) { _increaseApproval(_spender, _addedValue, msg.sender); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * @notice decreaseApproval should be used instead of approve when the user's allowance * is greater than 0. Using decreaseApproval protects against potential double-spend attacks * by moving the check of whether the user has spent their allowance to the time that the transaction * is mined, removing the user's ability to double-spend * @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 userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) { _decreaseApproval(_spender, _subtractedValue, msg.sender); return true; } /** * @notice Destroy the tokens owned by a blacklisted account. This function can generally * only be called by a central authority. * @dev Should be access-restricted with the 'requiresPermission' modifier when implementing. * @param _who Account to destroy tokens from. Must be a blacklisted account. */ function destroyBlacklistedTokens(address _who, uint256 _amount) public userBlacklisted(_who) whenNotPaused requiresPermission { tokenStorage.subBalance(_who, _amount); tokenStorage.subTotalSupply(_amount); emit DestroyedBlacklistedTokens(_who, _amount); } /** * @notice Allows a central authority to approve themselves as a spender on a blacklisted account. * By default, the allowance is set to the balance of the blacklisted account, so that the * authority has full control over the account balance. * @dev Should be access-restricted with the 'requiresPermission' modifier when implementing. * @param _blacklistedAccount The blacklisted account. */ function approveBlacklistedAddressSpender(address _blacklistedAccount) public userBlacklisted(_blacklistedAccount) whenNotPaused requiresPermission { tokenStorage.setAllowance(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount)); emit ApprovedBlacklistedAddressSpender(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount)); } /** * @notice Initiates a "send" operation towards another user. See `transferFrom` for details. * @param _to The address of the receiver. This user must not be blacklisted, or else the tranfer * will fail. * @param _amount The number of tokens to transfer * * @return `true` if successful */ function transfer(address _to, uint256 _amount) public userNotBlacklisted(_to) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) { _transfer(_to, msg.sender, _amount); return true; } /** * @notice Initiates a transfer operation between address `_from` and `_to`. Requires that the * message sender is an approved spender on the _from account. * @dev When implemented, it should use the transferFromConditionsRequired() modifier. * @param _to The address of the recipient. This address must not be blacklisted. * @param _from The address of the origin of funds. This address _could_ be blacklisted, because * a regulator may want to transfer tokens out of a blacklisted account, for example. * In order to do so, the regulator would have to add themselves as an approved spender * on the account via `addBlacklistAddressSpender()`, and would then be able to transfer tokens out of it. * @param _amount The number of tokens to transfer * @return `true` if successful */ function transferFrom(address _from, address _to, uint256 _amount) public whenNotPaused transferFromConditionsRequired(_from, _to) returns (bool) { require(_amount <= allowance(_from, msg.sender),"not enough allowance to transfer"); _transfer(_to, _from, _amount); tokenStorage.subAllowance(_from, msg.sender, _amount); return true; } /** * * @dev Only the token owner can change its regulator * @param _newRegulator the new Regulator for this token * */ function setRegulator(address _newRegulator) public onlyOwner { require(_newRegulator != address(regulator), "Must be a new regulator"); require(AddressUtils.isContract(_newRegulator), "Cannot set a regulator storage to a non-contract address"); address old = address(regulator); regulator = Regulator(_newRegulator); emit ChangedRegulator(old, _newRegulator); } /** * @notice If a user is blacklisted, they will have the permission to * execute this dummy function. This function effectively acts as a marker * to indicate that a user is blacklisted. We include this function to be consistent with our * invariant that every possible userPermission (listed in Regulator) enables access to a single * PermissionedToken function. Thus, the 'BLACKLISTED' permission gives access to this function * @return `true` if successful */ function blacklisted() public view requiresPermission returns (bool) { return true; } /** * ERC20 standard functions */ function allowance(address owner, address spender) public view returns (uint256) { return tokenStorage.allowances(owner, spender); } function totalSupply() public view returns (uint256) { return tokenStorage.totalSupply(); } function balanceOf(address _addr) public view returns (uint256) { return tokenStorage.balances(_addr); } /** Internal functions **/ function _decreaseApproval(address _spender, uint256 _subtractedValue, address _tokenHolder) internal { uint256 oldValue = allowance(_tokenHolder, _spender); if (_subtractedValue > oldValue) { tokenStorage.setAllowance(_tokenHolder, _spender, 0); } else { tokenStorage.subAllowance(_tokenHolder, _spender, _subtractedValue); } emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender)); } function _increaseApproval(address _spender, uint256 _addedValue, address _tokenHolder) internal { tokenStorage.addAllowance(_tokenHolder, _spender, _addedValue); emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender)); } function _burn(address _tokensOf, uint256 _amount) internal { require(_tokensOf != address(0),"burner address cannot be 0x0"); require(_amount <= balanceOf(_tokensOf),"not enough balance to burn"); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure tokenStorage.subBalance(_tokensOf, _amount); tokenStorage.subTotalSupply(_amount); emit Burn(_tokensOf, _amount); emit Transfer(_tokensOf, address(0), _amount); } function _mint(address _to, uint256 _amount) internal { require(_to != address(0),"to address cannot be 0x0"); tokenStorage.addTotalSupply(_amount); tokenStorage.addBalance(_to, _amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); } function _transfer(address _to, address _from, uint256 _amount) internal { require(_to != address(0),"to address cannot be 0x0"); require(_amount <= balanceOf(_from),"not enough balance to transfer"); tokenStorage.addBalance(_to, _amount); tokenStorage.subBalance(_from, _amount); emit Transfer(_from, _to, _amount); } } /** * @title WhitelistedToken * @notice A WhitelistedToken can be converted into CUSD and vice versa. Converting a WT into a CUSD * is the only way for a user to obtain CUSD. This is a permissioned token, so users have to be * whitelisted before they can do any mint/burn/convert operation. */ contract WhitelistedToken is PermissionedToken { address public cusdAddress; /** Events */ event CUSDAddressChanged(address indexed oldCUSD, address indexed newCUSD); event MintedToCUSD(address indexed user, uint256 amount); event ConvertedToCUSD(address indexed user, uint256 amount); /** * @notice Constructor sets the regulator contract and the address of the * CarbonUSD meta-token contract. The latter is necessary in order to make transactions * with the CarbonDollar smart contract. */ constructor(address _regulator, address _cusd) public PermissionedToken(_regulator) { // base class fields regulator = Regulator(_regulator); cusdAddress = _cusd; } /** * @notice Mints CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD * into the CarbonUSD contract's escrow account. * @param _to The address of the receiver * @param _amount The number of CarbonTokens to mint to user */ function mintCUSD(address _to, uint256 _amount) public requiresPermission whenNotPaused userNotBlacklisted(_to) { return _mintCUSD(_to, _amount); } /** * @notice Converts WT0 to CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD * into the CarbonUSD contract's escrow account. * @param _amount The number of Whitelisted tokens to convert */ function convertWT(uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused { require(balanceOf(msg.sender) >= _amount, "Conversion amount should be less than balance"); _burn(msg.sender, _amount); _mintCUSD(msg.sender, _amount); emit ConvertedToCUSD(msg.sender, _amount); } /** * @notice Change the cusd address. * @param _cusd the cusd address. */ function setCUSDAddress(address _cusd) public onlyOwner { require(_cusd != address(cusdAddress), "Must be a new cusd address"); require(AddressUtils.isContract(_cusd), "Must be an actual contract"); address oldCUSD = address(cusdAddress); cusdAddress = _cusd; emit CUSDAddressChanged(oldCUSD, _cusd); } function _mintCUSD(address _to, uint256 _amount) internal { require(_to != cusdAddress, "Cannot mint to CarbonUSD contract"); // This is to prevent Carbon Labs from printing money out of thin air! CarbonDollar(cusdAddress).mint(_to, _amount); _mint(cusdAddress, _amount); emit MintedToCUSD(_to, _amount); } } /** * @title CarbonDollar * @notice The main functionality for the CarbonUSD metatoken. (CarbonUSD is just a proxy * that implements this contract's functionality.) This is a permissioned token, so users have to be * whitelisted before they can do any mint/burn/convert operation. Every CarbonDollar token is backed by one * whitelisted stablecoin credited to the balance of this contract address. */ contract CarbonDollar is PermissionedToken { // Events event ConvertedToWT(address indexed user, uint256 amount); event BurnedCUSD(address indexed user, uint256 feedAmount, uint256 chargedFee); /** Modifiers */ modifier requiresWhitelistedToken() { require(isWhitelisted(msg.sender), "Sender must be a whitelisted token contract"); _; } CarbonDollarStorage public tokenStorage_CD; /** CONSTRUCTOR * @dev Passes along arguments to base class. */ constructor(address _regulator) public PermissionedToken(_regulator) { // base class override regulator = Regulator(_regulator); tokenStorage_CD = new CarbonDollarStorage(); } /** * @notice Add new stablecoin to whitelist. * @param _stablecoin Address of stablecoin contract. */ function listToken(address _stablecoin) public onlyOwner whenNotPaused { tokenStorage_CD.addStablecoin(_stablecoin); } /** * @notice Remove existing stablecoin from whitelist. * @param _stablecoin Address of stablecoin contract. */ function unlistToken(address _stablecoin) public onlyOwner whenNotPaused { tokenStorage_CD.removeStablecoin(_stablecoin); } /** * @notice Change fees associated with going from CarbonUSD to a particular stablecoin. * @param stablecoin Address of the stablecoin contract. * @param _newFee The new fee rate to set, in tenths of a percent. */ function setFee(address stablecoin, uint256 _newFee) public onlyOwner whenNotPaused { require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee"); tokenStorage_CD.setFee(stablecoin, _newFee); } /** * @notice Remove fees associated with going from CarbonUSD to a particular stablecoin. * The default fee still may apply. * @param stablecoin Address of the stablecoin contract. */ function removeFee(address stablecoin) public onlyOwner whenNotPaused { require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee"); tokenStorage_CD.removeFee(stablecoin); } /** * @notice Change the default fee associated with going from CarbonUSD to a WhitelistedToken. * This fee amount is used if the fee for a WhitelistedToken is not specified. * @param _newFee The new fee rate to set, in tenths of a percent. */ function setDefaultFee(uint256 _newFee) public onlyOwner whenNotPaused { tokenStorage_CD.setDefaultFee(_newFee); } /** * @notice Mints CUSD on behalf of a user. Note the use of the "requiresWhitelistedToken" * modifier; this means that minting authority does not belong to any personal account; * only whitelisted token contracts can call this function. The intended functionality is that the only * way to mint CUSD is for the user to actually burn a whitelisted token to convert into CUSD * @param _to User to send CUSD to * @param _amount Amount of CarbonUSD to mint. */ function mint(address _to, uint256 _amount) public requiresWhitelistedToken whenNotPaused { _mint(_to, _amount); } /** * @notice user can convert CarbonUSD umbrella token into a whitelisted stablecoin. * @param stablecoin represents the type of coin the users wishes to receive for burning carbonUSD * @param _amount Amount of CarbonUSD to convert. * we credit the user's account at the sender address with the _amount minus the percentage fee we want to charge. */ function convertCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused { require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee"); WhitelistedToken whitelisted = WhitelistedToken(stablecoin); require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning"); // Send back WT0 to calling user, but with a fee reduction. // Transfer this fee into the whitelisted token's CarbonDollar account (this contract's address) uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(stablecoin)); uint256 feedAmount = _amount.sub(chargedFee); _burn(msg.sender, _amount); require(whitelisted.transfer(msg.sender, feedAmount)); whitelisted.burn(chargedFee); _mint(address(this), chargedFee); emit ConvertedToWT(msg.sender, _amount); } /** * @notice burns CarbonDollar and an equal amount of whitelisted stablecoin from the CarbonDollar address * @param stablecoin Represents the stablecoin whose fee will be charged. * @param _amount Amount of CarbonUSD to burn. */ function burnCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused { _burnCarbonDollar(msg.sender, stablecoin, _amount); } /** * @notice release collected CUSD fees to owner * @param _amount Amount of CUSD to release * @return `true` if successful */ function releaseCarbonDollar(uint256 _amount) public onlyOwner returns (bool) { require(_amount <= balanceOf(address(this)),"not enough balance to transfer"); tokenStorage.subBalance(address(this), _amount); tokenStorage.addBalance(msg.sender, _amount); emit Transfer(address(this), msg.sender, _amount); return true; } /** Computes fee percentage associated with burning into a particular stablecoin. * @param stablecoin The stablecoin whose fee will be charged. Precondition: is a whitelisted * stablecoin. * @return The fee that will be charged. If the stablecoin's fee is not set, the default * fee is returned. */ function computeFeeRate(address stablecoin) public view returns (uint256 feeRate) { if (getFee(stablecoin) > 0) feeRate = getFee(stablecoin); else feeRate = getDefaultFee(); } /** * @notice Check if whitelisted token is whitelisted * @return bool true if whitelisted, false if not **/ function isWhitelisted(address _stablecoin) public view returns (bool) { return tokenStorage_CD.whitelist(_stablecoin); } /** * @notice Get the fee associated with going from CarbonUSD to a specific WhitelistedToken. * @param stablecoin The stablecoin whose fee is being checked. * @return The fee associated with the stablecoin. */ function getFee(address stablecoin) public view returns (uint256) { return tokenStorage_CD.fees(stablecoin); } /** * @notice Get the default fee associated with going from CarbonUSD to a specific WhitelistedToken. * @return The default fee for stablecoin trades. */ function getDefaultFee() public view returns (uint256) { return tokenStorage_CD.defaultFee(); } function _burnCarbonDollar(address _tokensOf, address _stablecoin, uint256 _amount) internal { require(isWhitelisted(_stablecoin), "Stablecoin must be whitelisted prior to burning"); WhitelistedToken whitelisted = WhitelistedToken(_stablecoin); require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning"); // Burn user's CUSD, but with a fee reduction. uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(_stablecoin)); uint256 feedAmount = _amount.sub(chargedFee); _burn(_tokensOf, _amount); whitelisted.burn(_amount); _mint(address(this), chargedFee); emit BurnedCUSD(_tokensOf, feedAmount, chargedFee); // Whitelisted trust account should send user feedAmount USD } } /** * @title MetaToken * @notice Extends the CarbonDollar token by providing functionality for users to interact with * the permissioned token contract without needing to pay gas fees. MetaToken will perform the * exact same actions as a normal CarbonDollar, but first it will validate a signature of the * hash of the parameters and ecrecover() a signature to prove the signer so everything is still * cryptographically backed. Then, instead of doing actions on behalf of msg.sender, * it will move the signer’s tokens. Finally, we can also wrap in a token reward to incentivise the relayer. * @notice inspiration from @austingriffith and @PhABCD for leading the meta-transaction innovations */ contract MetaToken is CarbonDollar { /** * @dev create a new CarbonDollar with a brand new data storage **/ constructor (address _regulator) CarbonDollar(_regulator) public { } /** Storage */ mapping (address => uint256) public replayNonce; /** ERC20 Metadata */ string public constant name = "CUSD"; string public constant symbol = "CUSD"; uint8 public constant decimals = 18; /** Functions **/ /** * @dev Verify and broadcast an increaseApproval() signed metatransaction. The msg.sender or "relayer" * will pay for the ETH gas fees since they are sending this transaction, and in exchange * the "signer" will pay CUSD to the relayer. * @notice increaseApproval should be used instead of approve when the user's allowance * is greater than 0. Using increaseApproval protects against potential double-spend attacks * by moving the check of whether the user has spent their allowance to the time that the transaction * is mined, removing the user's ability to double-spend * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender * @param _nonce to prevent replay attack of metatransactions * @param _reward amount of CUSD to pay relayer in * @return `true` if successful */ function metaIncreaseApproval(address _spender, uint256 _addedValue, bytes _signature, uint256 _nonce, uint256 _reward) public userNotBlacklisted(_spender) whenNotPaused returns (bool) { bytes32 metaHash = metaApproveHash(_spender, _addedValue, _nonce, _reward); address signer = _getSigner(metaHash, _signature); require(!regulator.isBlacklistedUser(signer), "signer is blacklisted"); require(_nonce == replayNonce[signer], "this transaction has already been broadcast"); replayNonce[signer]++; require( _reward > 0, "reward to incentivize relayer must be positive"); require( _reward <= balanceOf(signer),"not enough balance to reward relayer"); _increaseApproval(_spender, _addedValue, signer); _transfer(msg.sender, signer, _reward); return true; } /** * @notice Verify and broadcast a transfer() signed metatransaction. The msg.sender or "relayer" * will pay for the ETH gas fees since they are sending this transaction, and in exchange * the "signer" will pay CUSD to the relayer. * @param _to The address of the receiver. This user must not be blacklisted, or else the transfer * will fail. * @param _amount The number of tokens to transfer * @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender * @param _nonce to prevent replay attack of metatransactions * @param _reward amount of CUSD to pay relayer in * @return `true` if successful */ function metaTransfer(address _to, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public userNotBlacklisted(_to) whenNotPaused returns (bool) { bytes32 metaHash = metaTransferHash(_to, _amount, _nonce, _reward); address signer = _getSigner(metaHash, _signature); require(!regulator.isBlacklistedUser(signer), "signer is blacklisted"); require(_nonce == replayNonce[signer], "this transaction has already been broadcast"); replayNonce[signer]++; require( _reward > 0, "reward to incentivize relayer must be positive"); require( (_amount + _reward) <= balanceOf(signer),"not enough balance to transfer and reward relayer"); _transfer(_to, signer, _amount); _transfer(msg.sender, signer, _reward); return true; } /** * @notice Verify and broadcast a burnCarbonDollar() signed metatransaction. The msg.sender or "relayer" * will pay for the ETH gas fees since they are sending this transaction, and in exchange * the "signer" will pay CUSD to the relayer. * @param _stablecoin Represents the stablecoin that is backing the active CUSD. * @param _amount The number of tokens to transfer * @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender * @param _nonce to prevent replay attack of metatransactions * @param _reward amount of CUSD to pay relayer in * @return `true` if successful */ function metaBurnCarbonDollar(address _stablecoin, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public whenNotPaused returns (bool) { bytes32 metaHash = metaBurnHash(_stablecoin, _amount, _nonce, _reward); address signer = _getSigner(metaHash, _signature); require(!regulator.isBlacklistedUser(signer), "signer is blacklisted"); require(_nonce == replayNonce[signer], "this transaction has already been broadcast"); replayNonce[signer]++; require( _reward > 0, "reward to incentivize relayer must be positive"); require( (_amount + _reward) <= balanceOf(signer),"not enough balance to burn and reward relayer"); _burnCarbonDollar(signer, _stablecoin, _amount); _transfer(msg.sender, signer, _reward); return true; } /** * @notice Return hash containing all of the information about the transfer() metatransaction * @param _to The address of the transfer receiver * @param _amount The number of tokens to transfer * @param _nonce to prevent replay attack of metatransactions * @param _reward amount of CUSD to pay relayer in * @return bytes32 hash of metatransaction */ function metaTransferHash(address _to, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){ return keccak256(abi.encodePacked(address(this),"metaTransfer", _to, _amount, _nonce, _reward)); } /** * @notice Return hash containing all of the information about the increaseApproval() metatransaction * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _nonce to prevent replay attack of metatransactions * @param _reward amount of CUSD to pay relayer in * @return bytes32 hash of metatransaction */ function metaApproveHash(address _spender, uint256 _addedValue, uint256 _nonce, uint256 _reward) public view returns(bytes32){ return keccak256(abi.encodePacked(address(this),"metaIncreaseApproval", _spender, _addedValue, _nonce, _reward)); } /** * @notice Return hash containing all of the information about the burnCarbonDollar() metatransaction * @param _stablecoin Represents the stablecoin that is backing the active CUSD. * @param _amount The number of tokens to burn * @param _nonce to prevent replay attack of metatransactions * @param _reward amount of CUSD to pay relayer in * @return bytes32 hash of metatransaction */ function metaBurnHash(address _stablecoin, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){ return keccak256(abi.encodePacked(address(this),"metaBurnCarbonDollar", _stablecoin, _amount, _nonce, _reward)); } /** * @dev Recover signer of original metatransaction * @param _hash derived bytes32 metatransaction signature, which should be the same as the parameter _signature * @param _signature bytes metatransaction signature, the signature is generated using web3.eth.sign() * @return address of hash signer */ function _getSigner(bytes32 _hash, bytes _signature) internal pure returns (address){ bytes32 r; bytes32 s; uint8 v; if (_signature.length != 65) { return address(0); } assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return address(0); } else { return ecrecover(keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash) ), v, r, s); } } }
Sets the necessary permissions for a user to destroy tokens from a blacklisted account. _who The address of the account that we are setting permissions for./
function setBlacklistDestroyer(address _who) public onlyValidator { require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token"); setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG); emit LogSetBlacklistDestroyer(_who); }
1,020,251
./full_match/80001/0xd18F4BcaF88c19570EaFb9376207ade8803BefC7/sources/_rarible/meta-tx/contracts/EIP712MetaTransaction.sol
Append userAddress at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "Function call not successful"); emit MetaTransactionExecuted(userAddress, msg.sender, functionSignature); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256(abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) )); }
863,887
pragma solidity 0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title 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; } } /** * @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 Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is 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, uint256 _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, uint256 _subtractedValue ) public returns (bool) { 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; } } /** * @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 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 Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract RepublicToken is PausableToken, BurnableToken { string public constant name = "Republic Token"; string public constant symbol = "REN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals); /// @notice The RepublicToken Constructor. constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { /* solium-disable error-reason */ require(amount > 0); balances[owner] = balances[owner].sub(amount); balances[beneficiary] = balances[beneficiary].add(amount); emit Transfer(owner, beneficiary, amount); return true; } } /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = 0x0; /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping (address => Node) list; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "not in list"); if (node == NULL) { return; } address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap(List storage self, address left, address right) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].previous; } } /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RepublicToken. RepublicToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RepublicToken contract. constructor( string _VERSION, RepublicToken _ren ) public { VERSION = _VERSION; ren = _ren; } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOwner The darknode's owner's address /// @param _bond The darknode's bond value /// @param _publicKey The darknode's public key /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address _darknodeOwner, uint256 _bond, bytes _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOwner, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store function begin() external view onlyOwner returns(address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns(address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require(ren.transfer(owner, bond), "bond transfer failed"); } /// @notice Updates the bond of the darknode. If the bond is being /// decreased, the difference is sent to the owner of this contract. function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; darknodeRegistry[darknodeID].bond = bond; if (previousBond > bond) { require(ren.transfer(owner, previousBond - bond), "cannot transfer bond"); } } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOwner(address darknodeID) external view onlyOwner returns (address) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) { return darknodeRegistry[darknodeID].publicKey; } } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocknumber; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; address public slasher; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; address public nextSlasher; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RepublicToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// @notice Emitted when a darknode is registered. /// @param _darknodeID The darknode ID that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeID The darknode ID that was deregistered. event LogDarknodeDeregistered(address _darknodeID); /// @notice Emitted when a refund has been made. /// @param _owner The address that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address _owner, uint256 _amount); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond); event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize); event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval); event LogSlasherUpdated(address previousSlasher, address nextSlasher); /// @notice Only allow the owner that registered the darknode to pass. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner"); _; } /// @notice Only allow unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "must be refunded or never registered"); _; } /// @notice Only allow refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "must be deregistered for at least one epoch"); _; } /// @notice Only allowed registered nodes without a pending deregistration to /// deregister modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "must be deregisterable"); _; } /// @notice Only allow the Slasher contract. modifier onlySlasher() { require(slasher == msg.sender, "must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RepublicToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochInterval The minimum number of blocks between /// epochs. constructor( string _VERSION, RepublicToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochInterval ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochInterval; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocknumber: block.number }); numDarknodes = 0; numDarknodesNextEpoch = 0; numDarknodesPreviousEpoch = 0; } /// @notice Register a darknode and transfer the bond to this contract. The /// caller must provide a public encryption key for the darknode as well as /// a bond in REN. The bond must be provided as an ERC20 allowance. The dark /// node will remain pending registration until the next epoch. Only after /// this period can the darknode be deregistered. The caller of this method /// will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. /// @param _bond The bond that will be paid. It must be greater than, or /// equal to, the minimum bond. function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) { // REN allowance require(_bond >= minimumBond, "insufficient bond"); // require(ren.allowance(msg.sender, address(this)) >= _bond); require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed"); ren.transfer(address(store), _bond); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, _bond, _publicKey, currentEpoch.blocknumber + minimumEpochInterval, 0 ); numDarknodesNextEpoch += 1; // Emit an event. emit LogDarknodeRegistered(_darknodeID, _bond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method store.darknodeRegisteredAt(_darknodeID) must be // the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; // Emit an event emit LogDarknodeDeregistered(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocknumber == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner, "not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocknumber: block.number }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(slasher, nextSlasher); } // Emit an event emit LogNewEpoch(); } /// @notice Allows the contract owner to transfer ownership of the /// DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(address _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash half of a darknode's /// bond and deregister it. The bond is distributed as follows: /// 1/2 is kept by the guilty prover /// 1/8 is rewarded to the first challenger /// 1/8 is rewarded to the second challenger /// 1/4 becomes unassigned /// @param _prover The guilty prover whose bond is being slashed /// @param _challenger1 The first of the two darknodes who submitted the challenge /// @param _challenger2 The second of the two darknodes who submitted the challenge function slash(address _prover, address _challenger1, address _challenger2) external onlySlasher { uint256 penalty = store.darknodeBond(_prover) / 2; uint256 reward = penalty / 4; // Slash the bond of the failed prover in half store.updateDarknodeBond(_prover, penalty); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_prover)) { store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; emit LogDarknodeDeregistered(_prover); } // Reward the challengers with less than the penalty so that it is not // worth challenging yourself ren.transfer(store.darknodeOwner(_challenger1), reward); ren.transfer(store.darknodeOwner(_challenger2), reward); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode owner. /// /// @param _darknodeID The darknode ID that will be refunded. The caller /// of this method must be the owner of this darknode. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOwner = store.darknodeOwner(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the owner by transferring REN ren.transfer(darknodeOwner, amount); // Emit an event. emit LogDarknodeOwnerRefunded(darknodeOwner, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOwner(address _darknodeID) external view returns (address) { return store.darknodeOwner(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return function isPendingRegistration(address _darknodeID) external view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) external view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode /// @param _epoch One of currentEpoch, previousEpoch function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == 0x0) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == 0x0) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } } /** * @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; } } /// @notice Implements safeTransfer, safeTransferFrom and /// safeApprove for CompatibleERC20. /// /// See https://github.com/ethereum/solidity/issues/4116 /// /// This library allows interacting with ERC20 tokens that implement any of /// these interfaces: /// /// (1) transfer returns true on success, false on failure /// (2) transfer returns true on success, reverts on failure /// (3) transfer returns nothing on success, reverts on failure /// /// Additionally, safeTransferFromWithFees will return the final token /// value received after accounting for token fees. library CompatibleERC20Functions { using SafeMath for uint256; /// @notice Calls transfer on the token and reverts if the call fails. function safeTransfer(address token, address to, uint256 amount) internal { CompatibleERC20(token).transfer(to, amount); require(previousReturnValue(), "transfer failed"); } /// @notice Calls transferFrom on the token and reverts if the call fails. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); } /// @notice Calls approve on the token and reverts if the call fails. function safeApprove(address token, address spender, uint256 amount) internal { CompatibleERC20(token).approve(spender, amount); require(previousReturnValue(), "approve failed"); } /// @notice Calls transferFrom on the token, reverts if the call fails and /// returns the value transferred after fees. function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) { uint256 balancesBefore = CompatibleERC20(token).balanceOf(to); CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); uint256 balancesAfter = CompatibleERC20(token).balanceOf(to); return Math.min256(amount, balancesAfter.sub(balancesBefore)); } /// @notice Checks the return value of the previous function. Returns true /// if the previous function returned 32 non-zero bytes or returned zero /// bytes. function previousReturnValue() private pure returns (bool) { uint256 returnData = 0; assembly { /* solium-disable-line security/no-inline-assembly */ // Switch on the number of bytes returned by the previous call switch returndatasize // 0 bytes: ERC20 of type (3), did not throw case 0 { returnData := 1 } // 32 bytes: ERC20 of types (1) or (2) case 32 { // Copy the return data into scratch space returndatacopy(0x0, 0x0, 32) // Load the return data into returnData returnData := mload(0x0) } // Other return size: return false default { } } return returnData != 0; } } /// @notice ERC20 interface which doesn't specify the return type for transfer, /// transferFrom and approve. interface CompatibleERC20 { // Modified to not return boolean function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; // Not modifier function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// @notice The DarknodeRewardVault contract is responsible for holding fees /// for darknodes for settling orders. Fees can be withdrawn to the address of /// the darknode's operator. Fees can be in ETH or in ERC20 tokens. /// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md contract DarknodeRewardVault is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; mapping(address => mapping(address => uint256)) public darknodeBalances; event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The DarknodeRegistry contract that is used by /// the vault to lookup Darknode owners. constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; } function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Deposit fees into the vault for a Darknode. The Darknode /// registration is not checked (to reduce gas fees); the caller must be /// careful not to call this function for a Darknode that is not registered /// otherwise any fees deposited to that Darknode can be withdrawn by a /// malicious adversary (by registering the Darknode before the honest /// party and claiming ownership). /// /// @param _darknode The address of the Darknode that will receive the /// fees. /// @param _token The address of the ERC20 token being used to pay the fee. /// A special address is used for Ether. /// @param _value The amount of fees in the smallest unit of the token. function deposit(address _darknode, ERC20 _token, uint256 _value) public payable { uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched ether value"); } else { require(msg.value == 0, "unexpected ether value"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value); } darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue); } /// @notice Withdraw fees earned by a Darknode. The fees will be sent to /// the owner of the Darknode. If a Darknode is not registered the fees /// cannot be withdrawn. /// /// @param _darknode The address of the Darknode whose fees are being /// withdrawn. The owner of this Darknode will receive the fees. /// @param _token The address of the ERC20 token to withdraw. function withdraw(address _darknode, ERC20 _token) public { address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode)); require(darknodeOwner != 0x0, "invalid darknode owner"); uint256 value = darknodeBalances[_darknode][_token]; darknodeBalances[_darknode][_token] = 0; if (address(_token) == ETHEREUM) { darknodeOwner.transfer(value); } else { CompatibleERC20(_token).safeTransfer(darknodeOwner, value); } } } /// @notice The BrokerVerifier interface defines the functions that a settlement /// layer's broker verifier contract must implement. interface BrokerVerifier { /// @notice The function signature that will be called when a trader opens /// an order. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature The 65-byte signature from the broker. /// @param _orderID The 32-byte order ID. function verifyOpenSignature( address _trader, bytes _signature, bytes32 _orderID ) external returns (bool); } /// @notice The Settlement interface defines the functions that a settlement /// layer must implement. /// Docs: https://github.com/republicprotocol/republic-sol/blob/nightly/docs/05-settlement.md interface Settlement { function submitOrder( bytes _details, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external; function submissionGasPriceLimit() external view returns (uint256); function settle( bytes32 _buyID, bytes32 _sellID ) external; /// @notice orderStatus should return the status of the order, which should /// be: /// 0 - Order not seen before /// 1 - Order details submitted /// >1 - Order settled, or settlement no longer possible function orderStatus(bytes32 _orderID) external view returns (uint8); } /// @notice SettlementRegistry allows a Settlement layer to register the /// contracts used for match settlement and for broker signature verification. contract SettlementRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. struct SettlementDetails { bool registered; Settlement settlementContract; BrokerVerifier brokerVerifierContract; } // Settlement IDs are 64-bit unsigned numbers mapping(uint64 => SettlementDetails) public settlementDetails; // Events event LogSettlementRegistered(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract); event LogSettlementUpdated(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract); event LogSettlementDeregistered(uint64 settlementID); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Returns the settlement contract of a settlement layer. function settlementRegistration(uint64 _settlementID) external view returns (bool) { return settlementDetails[_settlementID].registered; } /// @notice Returns the settlement contract of a settlement layer. function settlementContract(uint64 _settlementID) external view returns (Settlement) { return settlementDetails[_settlementID].settlementContract; } /// @notice Returns the broker verifier contract of a settlement layer. function brokerVerifierContract(uint64 _settlementID) external view returns (BrokerVerifier) { return settlementDetails[_settlementID].brokerVerifierContract; } /// @param _settlementID A unique 64-bit settlement identifier. /// @param _settlementContract The address to use for settling matches. /// @param _brokerVerifierContract The decimals to use for verifying /// broker signatures. function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner { bool alreadyRegistered = settlementDetails[_settlementID].registered; settlementDetails[_settlementID] = SettlementDetails({ registered: true, settlementContract: _settlementContract, brokerVerifierContract: _brokerVerifierContract }); if (alreadyRegistered) { emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract); } else { emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract); } } /// @notice Deregisteres a settlement layer, clearing the details. /// @param _settlementID The unique 64-bit settlement identifier. function deregisterSettlement(uint64 _settlementID) external onlyOwner { require(settlementDetails[_settlementID].registered, "not registered"); delete settlementDetails[_settlementID]; emit LogSettlementDeregistered(_settlementID); } } /** * @title Eliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * 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:" * 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) ); } } library Utils { /** * @notice Converts a number to its string/bytes representation * * @param _v the uint to convert */ function uintToBytes(uint256 _v) internal pure returns (bytes) { uint256 v = _v; if (v == 0) { return "0"; } uint256 digits = 0; uint256 v2 = v; while (v2 > 0) { v2 /= 10; digits += 1; } bytes memory result = new bytes(digits); for (uint256 i = 0; i < digits; i++) { result[digits - i - 1] = bytes1((v % 10) + 48); v /= 10; } return result; } /** * @notice Retrieves the address from a signature * * @param _hash the message that was signed (any length of bytes) * @param _signature the signature (65 bytes) */ function addr(bytes _hash, bytes _signature) internal pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash); bytes32 prefixedHash = keccak256(encoded); return ECRecovery.recover(prefixedHash, _signature); } } /// @notice The Orderbook contract stores the state and priority of orders and /// allows the Darknodes to easily reach consensus. Eventually, this contract /// will only store a subset of order states, such as cancellation, to improve /// the throughput of orders. contract Orderbook is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice OrderState enumerates the possible states of an order. All /// orders default to the Undefined state. enum OrderState {Undefined, Open, Confirmed, Canceled} /// @notice Order stores a subset of the public data associated with an order. struct Order { OrderState state; // State of the order address trader; // Trader that owns the order address confirmer; // Darknode that confirmed the order in a match uint64 settlementID; // The settlement that signed the order opening uint256 priority; // Logical time priority of this order uint256 blockNumber; // Block number of the most recent state change bytes32 matchedOrder; // Order confirmed in a match with this order } DarknodeRegistry public darknodeRegistry; SettlementRegistry public settlementRegistry; bytes32[] private orderbook; // Order details are exposed through directly accessing this mapping, or // through the getter functions below for each of the order's fields. mapping(bytes32 => Order) public orders; event LogFeeUpdated(uint256 previousFee, uint256 nextFee); event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice Only allow registered dark nodes. modifier onlyDarknode(address _sender) { require(darknodeRegistry.isRegistered(address(_sender)), "must be registered darknode"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The address of the DarknodeRegistry contract. /// @param _settlementRegistry The address of the SettlementRegistry /// contract. constructor( string _VERSION, DarknodeRegistry _darknodeRegistry, SettlementRegistry _settlementRegistry ) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; settlementRegistry = _settlementRegistry; } /// @notice Allows the owner to update the address of the DarknodeRegistry /// contract. function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) external onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Open an order in the orderbook. The order must be in the /// Undefined state. /// /// @param _signature Signature of the message that defines the trader. The /// message is "Republic Protocol: open: {orderId}". /// @param _orderID The hash of the order. function openOrder(uint64 _settlementID, bytes _signature, bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Undefined, "invalid order status"); address trader = msg.sender; // Verify the order signature require(settlementRegistry.settlementRegistration(_settlementID), "settlement not registered"); BrokerVerifier brokerVerifier = settlementRegistry.brokerVerifierContract(_settlementID); require(brokerVerifier.verifyOpenSignature(trader, _signature, _orderID), "invalid broker signature"); orders[_orderID] = Order({ state: OrderState.Open, trader: trader, confirmer: 0x0, settlementID: _settlementID, priority: orderbook.length + 1, blockNumber: block.number, matchedOrder: 0x0 }); orderbook.push(_orderID); } /// @notice Confirm an order match between orders. The confirmer must be a /// registered Darknode and the orders must be in the Open state. A /// malicious confirmation by a Darknode will result in a bond slash of the /// Darknode. /// /// @param _orderID The hash of the order. /// @param _matchedOrderID The hashes of the matching order. function confirmOrder(bytes32 _orderID, bytes32 _matchedOrderID) external onlyDarknode(msg.sender) { require(orders[_orderID].state == OrderState.Open, "invalid order status"); require(orders[_matchedOrderID].state == OrderState.Open, "invalid order status"); orders[_orderID].state = OrderState.Confirmed; orders[_orderID].confirmer = msg.sender; orders[_orderID].matchedOrder = _matchedOrderID; orders[_orderID].blockNumber = block.number; orders[_matchedOrderID].state = OrderState.Confirmed; orders[_matchedOrderID].confirmer = msg.sender; orders[_matchedOrderID].matchedOrder = _orderID; orders[_matchedOrderID].blockNumber = block.number; } /// @notice Cancel an open order in the orderbook. An order can be cancelled /// by the trader who opened the order, or by the broker verifier contract. /// This allows the settlement layer to implement their own logic for /// cancelling orders without trader interaction (e.g. to ban a trader from /// a specific darkpool, or to use multiple order-matching platforms) /// /// @param _orderID The hash of the order. function cancelOrder(bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Open, "invalid order state"); // Require the msg.sender to be the trader or the broker verifier address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settlementID)); require(msg.sender == orders[_orderID].trader || msg.sender == brokerVerifier, "not authorized"); orders[_orderID].state = OrderState.Canceled; orders[_orderID].blockNumber = block.number; } /// @notice returns status of the given orderID. function orderState(bytes32 _orderID) external view returns (OrderState) { return orders[_orderID].state; } /// @notice returns a list of matched orders to the given orderID. function orderMatch(bytes32 _orderID) external view returns (bytes32) { return orders[_orderID].matchedOrder; } /// @notice returns the priority of the given orderID. /// The priority is the index of the order in the orderbook. function orderPriority(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].priority; } /// @notice returns the trader of the given orderID. /// Trader is the one who signs the message and does the actual trading. function orderTrader(bytes32 _orderID) external view returns (address) { return orders[_orderID].trader; } /// @notice returns the darknode address which confirms the given orderID. function orderConfirmer(bytes32 _orderID) external view returns (address) { return orders[_orderID].confirmer; } /// @notice returns the block number when the order being last modified. function orderBlockNumber(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].blockNumber; } /// @notice returns the block depth of the orderId function orderDepth(bytes32 _orderID) external view returns (uint256) { if (orders[_orderID].blockNumber == 0) { return 0; } return (block.number - orders[_orderID].blockNumber); } /// @notice returns the number of orders in the orderbook function ordersCount() external view returns (uint256) { return orderbook.length; } /// @notice returns order details of the orders starting from the offset. function getOrders(uint256 _offset, uint256 _limit) external view returns (bytes32[], address[], uint8[]) { if (_offset >= orderbook.length) { return; } // If the provided limit is more than the number of orders after the offset, // decrease the limit uint256 limit = _limit; if (_offset + limit > orderbook.length) { limit = orderbook.length - _offset; } bytes32[] memory orderIDs = new bytes32[](limit); address[] memory traderAddresses = new address[](limit); uint8[] memory states = new uint8[](limit); for (uint256 i = 0; i < limit; i++) { bytes32 order = orderbook[i + _offset]; orderIDs[i] = order; traderAddresses[i] = orders[order].trader; states[i] = uint8(orders[order].state); } return (orderIDs, traderAddresses, states); } } /// @notice A library for calculating and verifying order match details library SettlementUtils { struct OrderDetails { uint64 settlementID; uint64 tokens; uint256 price; uint256 volume; uint256 minimumVolume; } /// @notice Calculates the ID of the order. /// @param details Order details that are not required for settlement /// execution. They are combined as a single byte array. /// @param order The order details required for settlement execution. function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) { return keccak256( abi.encodePacked( details, order.settlementID, order.tokens, order.price, order.volume, order.minimumVolume ) ); } /// @notice Verifies that two orders match when considering the tokens, /// price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used /// my the DarknodeSlasher to verify challenges. Settlement layers may also /// use this function. /// @dev When verifying two orders for settlement, you should also: /// 1) verify the orders have been confirmed together /// 2) verify the orders' traders are distinct /// @param _buy The buy order details. /// @param _sell The sell order details. function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) { // Buy and sell tokens should match if (!verifyTokens(_buy.tokens, _sell.tokens)) { return false; } // Buy price should be greater than sell price if (_buy.price < _sell.price) { return false; } // // Buy volume should be greater than sell minimum volume if (_buy.volume < _sell.minimumVolume) { return false; } // Sell volume should be greater than buy minimum volume if (_sell.volume < _buy.minimumVolume) { return false; } // Require that the orders were submitted to the same settlement layer if (_buy.settlementID != _sell.settlementID) { return false; } return true; } /// @notice Verifies that two token requirements can be matched and that the /// tokens are formatted correctly. /// @param _buyTokens The buy token details. /// @param _sellToken The sell token details. function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) { return (( uint32(_buyTokens) == uint32(_sellToken >> 32)) && ( uint32(_sellToken) == uint32(_buyTokens >> 32)) && ( uint32(_buyTokens >> 32) <= uint32(_buyTokens)) ); } } /// @notice RenExTokens is a registry of tokens that can be traded on RenEx. contract RenExTokens is Ownable { string public VERSION; // Passed in as a constructor parameter. struct TokenDetails { address addr; uint8 decimals; bool registered; } // Storage mapping(uint32 => TokenDetails) public tokens; mapping(uint32 => bool) private detailsSubmitted; // Events event LogTokenRegistered(uint32 tokenCode, address tokenAddress, uint8 tokenDecimals); event LogTokenDeregistered(uint32 tokenCode); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Allows the owner to register and the details for a token. /// Once details have been submitted, they cannot be overwritten. /// To re-register the same token with different details (e.g. if the address /// has changed), a different token identifier should be used and the /// previous token identifier should be deregistered. /// If a token is not Ethereum-based, the address will be set to 0x0. /// /// @param _tokenCode A unique 32-bit token identifier. /// @param _tokenAddress The address of the token. /// @param _tokenDecimals The decimals to use for the token. function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner { require(!tokens[_tokenCode].registered, "already registered"); // If a token is being re-registered, the same details must be provided. if (detailsSubmitted[_tokenCode]) { require(tokens[_tokenCode].addr == _tokenAddress, "different address"); require(tokens[_tokenCode].decimals == _tokenDecimals, "different decimals"); } else { detailsSubmitted[_tokenCode] = true; } tokens[_tokenCode] = TokenDetails({ addr: _tokenAddress, decimals: _tokenDecimals, registered: true }); emit LogTokenRegistered(_tokenCode, _tokenAddress, _tokenDecimals); } /// @notice Sets a token as being deregistered. The details are still stored /// to prevent the token from being re-registered with different details. /// /// @param _tokenCode The unique 32-bit token identifier. function deregisterToken(uint32 _tokenCode) external onlyOwner { require(tokens[_tokenCode].registered, "not registered"); tokens[_tokenCode].registered = false; emit LogTokenDeregistered(_tokenCode); } } /// @notice RenExSettlement implements the Settlement interface. It implements /// the on-chain settlement for the RenEx settlement layer, and the fee payment /// for the RenExAtomic settlement layer. contract RenExSettlement is Ownable { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. // This contract handles the settlements with ID 1 and 2. uint32 constant public RENEX_SETTLEMENT_ID = 1; uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2; // Fees in RenEx are 0.2%. To represent this as integers, it is broken into // a numerator and denominator. uint256 constant public DARKNODE_FEES_NUMERATOR = 2; uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000; // Constants used in the price / volume inputs. int16 constant private PRICE_OFFSET = 12; int16 constant private VOLUME_OFFSET = 12; // Constructor parameters, updatable by the owner Orderbook public orderbookContract; RenExTokens public renExTokensContract; RenExBalances public renExBalancesContract; address public slasherAddress; uint256 public submissionGasPriceLimit; enum OrderStatus {None, Submitted, Settled, Slashed} struct TokenPair { RenExTokens.TokenDetails priorityToken; RenExTokens.TokenDetails secondaryToken; } // A uint256 tuple representing a value and an associated fee struct ValueWithFees { uint256 value; uint256 fees; } // A uint256 tuple representing a fraction struct Fraction { uint256 numerator; uint256 denominator; } // We use left and right because the tokens do not always represent the // priority and secondary tokens. struct SettlementDetails { uint256 leftVolume; uint256 rightVolume; uint256 leftTokenFee; uint256 rightTokenFee; address leftTokenAddress; address rightTokenAddress; } // Events event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook); event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens); event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances); event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit); event LogSlasherUpdated(address previousSlasher, address nextSlasher); // Order Storage mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails; mapping(bytes32 => address) public orderSubmitter; mapping(bytes32 => OrderStatus) public orderStatus; // Match storage (match details are indexed by [buyID][sellID]) mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp; /// @notice Prevents a function from being called with a gas price higher /// than the specified limit. /// /// @param _gasPriceLimit The gas price upper-limit in Wei. modifier withGasPriceLimit(uint256 _gasPriceLimit) { require(tx.gasprice <= _gasPriceLimit, "gas price too high"); _; } /// @notice Restricts a function to only being called by the slasher /// address. modifier onlySlasher() { require(msg.sender == slasherAddress, "unauthorized"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _orderbookContract The address of the Orderbook contract. /// @param _renExBalancesContract The address of the RenExBalances /// contract. /// @param _renExTokensContract The address of the RenExTokens contract. constructor( string _VERSION, Orderbook _orderbookContract, RenExTokens _renExTokensContract, RenExBalances _renExBalancesContract, address _slasherAddress, uint256 _submissionGasPriceLimit ) public { VERSION = _VERSION; orderbookContract = _orderbookContract; renExTokensContract = _renExTokensContract; renExBalancesContract = _renExBalancesContract; slasherAddress = _slasherAddress; submissionGasPriceLimit = _submissionGasPriceLimit; } /// @notice The owner of the contract can update the Orderbook address. /// @param _newOrderbookContract The address of the new Orderbook contract. function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner { emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract); orderbookContract = _newOrderbookContract; } /// @notice The owner of the contract can update the RenExTokens address. /// @param _newRenExTokensContract The address of the new RenExTokens /// contract. function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner { emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract); renExTokensContract = _newRenExTokensContract; } /// @notice The owner of the contract can update the RenExBalances address. /// @param _newRenExBalancesContract The address of the new RenExBalances /// contract. function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner { emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract); renExBalancesContract = _newRenExBalancesContract; } /// @notice The owner of the contract can update the order submission gas /// price limit. /// @param _newSubmissionGasPriceLimit The new gas price limit. function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner { emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit); submissionGasPriceLimit = _newSubmissionGasPriceLimit; } /// @notice The owner of the contract can update the slasher address. /// @param _newSlasherAddress The new slasher address. function updateSlasher(address _newSlasherAddress) external onlyOwner { emit LogSlasherUpdated(slasherAddress, _newSlasherAddress); slasherAddress = _newSlasherAddress; } /// @notice Stores the details of an order. /// /// @param _prefix The miscellaneous details of the order required for /// calculating the order id. /// @param _settlementID The settlement identifier. /// @param _tokens The encoding of the token pair (buy token is encoded as /// the first 32 bytes and sell token is encoded as the last 32 /// bytes). /// @param _price The price of the order. Interpreted as the cost for 1 /// standard unit of the non-priority token, in 1e12 (i.e. /// PRICE_OFFSET) units of the priority token). /// @param _volume The volume of the order. Interpreted as the maximum /// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority /// token that can be traded by this order. /// @param _minimumVolume The minimum volume the trader is willing to /// accept. Encoded the same as the volume. function submitOrder( bytes _prefix, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external withGasPriceLimit(submissionGasPriceLimit) { SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({ settlementID: _settlementID, tokens: _tokens, price: _price, volume: _volume, minimumVolume: _minimumVolume }); bytes32 orderID = SettlementUtils.hashOrder(_prefix, order); require(orderStatus[orderID] == OrderStatus.None, "order already submitted"); require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order"); orderSubmitter[orderID] = msg.sender; orderStatus[orderID] = OrderStatus.Submitted; orderDetails[orderID] = order; } /// @notice Settles two orders that are matched. `submitOrder` must have been /// called for each order before this function is called. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. function settle(bytes32 _buyID, bytes32 _sellID) external { require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status"); require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status"); // Check the settlement ID (only have to check for one, since // `verifyMatchDetails` checks that they are the same) require( orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID || orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID, "invalid settlement id" ); // Verify that the two order details are compatible. require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders"); // Verify that the two orders have been confirmed to one another. require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders"); // Retrieve token details. TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens); // Require that the tokens have been registered. require(tokens.priorityToken.registered, "unregistered priority token"); require(tokens.secondaryToken.registered, "unregistered secondary token"); address buyer = orderbookContract.orderTrader(_buyID); address seller = orderbookContract.orderTrader(_sellID); require(buyer != seller, "orders from same trader"); execute(_buyID, _sellID, buyer, seller, tokens); /* solium-disable-next-line security/no-block-members */ matchTimestamp[_buyID][_sellID] = now; // Store that the orders have been settled. orderStatus[_buyID] = OrderStatus.Settled; orderStatus[_sellID] = OrderStatus.Settled; } /// @notice Slashes the bond of a guilty trader. This is called when an /// atomic swap is not executed successfully. /// To open an atomic order, a trader must have a balance equivalent to /// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in /// darknode fees when the order is matched. If the remaining amount is /// is slashed, it is distributed as follows: /// 1) 0.2% goes to the other trader, covering their fee /// 2) 0.2% goes to the slasher address /// Only one order in a match can be slashed. /// /// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader. function slash(bytes32 _guiltyOrderID) external onlySlasher { require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade"); bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID); require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status"); require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status"); orderStatus[_guiltyOrderID] = OrderStatus.Slashed; (bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ? (_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID); TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens); SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens); // Transfer the fee amount to the other trader renExBalancesContract.transferBalanceWithFee( orderbookContract.orderTrader(_guiltyOrderID), orderbookContract.orderTrader(innocentOrderID), settlementDetails.leftTokenAddress, settlementDetails.leftTokenFee, 0, 0x0 ); // Transfer the fee amount to the slasher renExBalancesContract.transferBalanceWithFee( orderbookContract.orderTrader(_guiltyOrderID), slasherAddress, settlementDetails.leftTokenAddress, settlementDetails.leftTokenFee, 0, 0x0 ); } /// @notice Retrieves the settlement details of an order. /// For atomic swaps, it returns the full volumes, not the settled fees. /// /// @param _orderID The order to lookup the details of. Can be the ID of a /// buy or a sell order. /// @return [ /// a boolean representing whether or not the order has been settled, /// a boolean representing whether or not the order is a buy /// the 32-byte order ID of the matched order /// the volume of the priority token, /// the volume of the secondary token, /// the fee paid in the priority token, /// the fee paid in the secondary token, /// the token code of the priority token, /// the token code of the secondary token /// ] function getMatchDetails(bytes32 _orderID) external view returns ( bool settled, bool orderIsBuy, bytes32 matchedID, uint256 priorityVolume, uint256 secondaryVolume, uint256 priorityFee, uint256 secondaryFee, uint32 priorityToken, uint32 secondaryToken ) { matchedID = orderbookContract.orderMatch(_orderID); orderIsBuy = isBuyOrder(_orderID); (bytes32 buyID, bytes32 sellID) = orderIsBuy ? (_orderID, matchedID) : (matchedID, _orderID); SettlementDetails memory settlementDetails = calculateSettlementDetails( buyID, sellID, getTokenDetails(orderDetails[buyID].tokens) ); return ( orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed, orderIsBuy, matchedID, settlementDetails.leftVolume, settlementDetails.rightVolume, settlementDetails.leftTokenFee, settlementDetails.rightTokenFee, uint32(orderDetails[buyID].tokens >> 32), uint32(orderDetails[buyID].tokens) ); } /// @notice Exposes the hashOrder function for computing a hash of an /// order's details. An order hash is used as its ID. See `submitOrder` /// for the parameter descriptions. /// /// @return The 32-byte hash of the order. function hashOrder( bytes _prefix, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external pure returns (bytes32) { return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({ settlementID: _settlementID, tokens: _tokens, price: _price, volume: _volume, minimumVolume: _minimumVolume })); } /// @notice Called by `settle`, executes the settlement for a RenEx order /// or distributes the fees for a RenExAtomic swap. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _buyer The address of the buy trader. /// @param _seller The address of the sell trader. /// @param _tokens The details of the priority and secondary tokens. function execute( bytes32 _buyID, bytes32 _sellID, address _buyer, address _seller, TokenPair memory _tokens ) private { // Calculate the fees for atomic swaps, and the settlement details // otherwise. SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ? settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) : settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens); // Transfer priority token value renExBalancesContract.transferBalanceWithFee( _buyer, _seller, settlementDetails.leftTokenAddress, settlementDetails.leftVolume, settlementDetails.leftTokenFee, orderSubmitter[_buyID] ); // Transfer secondary token value renExBalancesContract.transferBalanceWithFee( _seller, _buyer, settlementDetails.rightTokenAddress, settlementDetails.rightVolume, settlementDetails.rightTokenFee, orderSubmitter[_sellID] ); } /// @notice Calculates the details required to execute two matched orders. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _tokens The details of the priority and secondary tokens. /// @return A struct containing the settlement details. function calculateSettlementDetails( bytes32 _buyID, bytes32 _sellID, TokenPair memory _tokens ) private view returns (SettlementDetails memory) { // Calculate the mid-price (using numerator and denominator to not loose // precision). Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2); // Calculate the lower of the two max volumes of each trader uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume); uint256 priorityTokenVolume = joinFraction( commonVolume.mul(midPrice.numerator), midPrice.denominator, int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET ); uint256 secondaryTokenVolume = joinFraction( commonVolume, 1, int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume); ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume); return SettlementDetails({ leftVolume: priorityVwF.value, rightVolume: secondaryVwF.value, leftTokenFee: priorityVwF.fees, rightTokenFee: secondaryVwF.fees, leftTokenAddress: _tokens.priorityToken.addr, rightTokenAddress: _tokens.secondaryToken.addr }); } /// @notice Calculates the fees to be transferred for an atomic swap. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _tokens The details of the priority and secondary tokens. /// @return A struct containing the fee details. function calculateAtomicFees( bytes32 _buyID, bytes32 _sellID, TokenPair memory _tokens ) private view returns (SettlementDetails memory) { // Calculate the mid-price (using numerator and denominator to not loose // precision). Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2); // Calculate the lower of the two max volumes of each trader uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume); if (isEthereumBased(_tokens.secondaryToken.addr)) { uint256 secondaryTokenVolume = joinFraction( commonVolume, 1, int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume); return SettlementDetails({ leftVolume: 0, rightVolume: 0, leftTokenFee: secondaryVwF.fees, rightTokenFee: secondaryVwF.fees, leftTokenAddress: _tokens.secondaryToken.addr, rightTokenAddress: _tokens.secondaryToken.addr }); } else if (isEthereumBased(_tokens.priorityToken.addr)) { uint256 priorityTokenVolume = joinFraction( commonVolume.mul(midPrice.numerator), midPrice.denominator, int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume); return SettlementDetails({ leftVolume: 0, rightVolume: 0, leftTokenFee: priorityVwF.fees, rightTokenFee: priorityVwF.fees, leftTokenAddress: _tokens.priorityToken.addr, rightTokenAddress: _tokens.priorityToken.addr }); } else { // Currently, at least one token must be Ethereum-based. // This will be implemented in the future. revert("non-eth atomic swaps are not supported"); } } /// @notice Order parity is set by the order tokens are listed. This returns /// whether an order is a buy or a sell. /// @return true if _orderID is a buy order. function isBuyOrder(bytes32 _orderID) private view returns (bool) { uint64 tokens = orderDetails[_orderID].tokens; uint32 firstToken = uint32(tokens >> 32); uint32 secondaryToken = uint32(tokens); return (firstToken < secondaryToken); } /// @return (value - fee, fee) where fee is 0.2% of value function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) { uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR; return ValueWithFees(newValue, _value - newValue); } /// @notice Gets the order details of the priority and secondary token from /// the RenExTokens contract and returns them as a single struct. /// /// @param _tokens The 64-bit combined token identifiers. /// @return A TokenPair struct containing two TokenDetails structs. function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) { ( address priorityAddress, uint8 priorityDecimals, bool priorityRegistered ) = renExTokensContract.tokens(uint32(_tokens >> 32)); ( address secondaryAddress, uint8 secondaryDecimals, bool secondaryRegistered ) = renExTokensContract.tokens(uint32(_tokens)); return TokenPair({ priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered), secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered) }); } /// @return true if _tokenAddress is 0x0, representing a token that is not /// on Ethereum function isEthereumBased(address _tokenAddress) private pure returns (bool) { return (_tokenAddress != address(0x0)); } /// @notice Computes (_numerator / _denominator) * 10 ** _scale function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) { if (_scale >= 0) { // Check that (10**_scale) doesn't overflow assert(_scale <= 77); // log10(2**256) = 77.06 return _numerator.mul(10 ** uint256(_scale)) / _denominator; } else { /// @dev If _scale is less than -77, 10**-_scale would overflow. // For now, -_scale > -24 (when a token has 0 decimals and // VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these // will be increased to add to more than 77. // assert((-_scale) <= 77); // log10(2**256) = 77.06 return (_numerator / _denominator) / 10 ** uint256(-_scale); } } } /// @notice RenExBrokerVerifier implements the BrokerVerifier contract, /// verifying broker signatures for order opening and fund withdrawal. contract RenExBrokerVerifier is Ownable { string public VERSION; // Passed in as a constructor parameter. // Events event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract); event LogBrokerRegistered(address broker); event LogBrokerDeregistered(address broker); // Storage mapping(address => bool) public brokers; mapping(address => uint256) public traderNonces; address public balancesContract; modifier onlyBalancesContract() { require(msg.sender == balancesContract, "not authorized"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Allows the owner of the contract to update the address of the /// RenExBalances contract. /// /// @param _balancesContract The address of the new balances contract function updateBalancesContract(address _balancesContract) external onlyOwner { emit LogBalancesContractUpdated(balancesContract, _balancesContract); balancesContract = _balancesContract; } /// @notice Approved an address to sign order-opening and withdrawals. /// @param _broker The address of the broker. function registerBroker(address _broker) external onlyOwner { require(!brokers[_broker], "already registered"); brokers[_broker] = true; emit LogBrokerRegistered(_broker); } /// @notice Reverts the a broker's registration. /// @param _broker The address of the broker. function deregisterBroker(address _broker) external onlyOwner { require(brokers[_broker], "not registered"); brokers[_broker] = false; emit LogBrokerDeregistered(_broker); } /// @notice Verifies a broker's signature for an order opening. /// The data signed by the broker is a prefixed message and the order ID. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature The 65-byte signature from the broker. /// @param _orderID The 32-byte order ID. /// @return True if the signature is valid, false otherwise. function verifyOpenSignature( address _trader, bytes _signature, bytes32 _orderID ) external view returns (bool) { bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID); address signer = Utils.addr(data, _signature); return (brokers[signer] == true); } /// @notice Verifies a broker's signature for a trader withdrawal. /// The data signed by the broker is a prefixed message, the trader address /// and a 256-bit trader nonce, which is incremented every time a valid /// signature is checked. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature 65-byte signature from the broker. /// @return True if the signature is valid, false otherwise. function verifyWithdrawSignature( address _trader, bytes _signature ) external onlyBalancesContract returns (bool) { bytes memory data = abi.encodePacked("Republic Protocol: withdraw: ", _trader, traderNonces[_trader]); address signer = Utils.addr(data, _signature); if (brokers[signer]) { traderNonces[_trader] += 1; return true; } return false; } } /// @notice RenExBalances is responsible for holding RenEx trader funds. contract RenExBalances is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. RenExSettlement public settlementContract; RenExBrokerVerifier public brokerVerifierContract; DarknodeRewardVault public rewardVaultContract; /// @dev Should match the address in the DarknodeRewardVault address constant public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Delay between a trader calling `withdrawSignal` and being able to call // `withdraw` without a broker signature. uint256 constant public SIGNAL_DELAY = 48 hours; // Events event LogBalanceDecreased(address trader, ERC20 token, uint256 value); event LogBalanceIncreased(address trader, ERC20 token, uint256 value); event LogRenExSettlementContractUpdated(address previousRenExSettlementContract, address newRenExSettlementContract); event LogRewardVaultContractUpdated(address previousRewardVaultContract, address newRewardVaultContract); event LogBrokerVerifierContractUpdated(address previousBrokerVerifierContract, address newBrokerVerifierContract); // Storage mapping(address => mapping(address => uint256)) public traderBalances; mapping(address => mapping(address => uint256)) public traderWithdrawalSignals; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _rewardVaultContract The address of the RewardVault contract. constructor( string _VERSION, DarknodeRewardVault _rewardVaultContract, RenExBrokerVerifier _brokerVerifierContract ) public { VERSION = _VERSION; rewardVaultContract = _rewardVaultContract; brokerVerifierContract = _brokerVerifierContract; } /// @notice Restricts a function to only being called by the RenExSettlement /// contract. modifier onlyRenExSettlementContract() { require(msg.sender == address(settlementContract), "not authorized"); _; } /// @notice Restricts trader withdrawing to be called if a signature from a /// RenEx broker is provided, or if a certain amount of time has passed /// since a trader has called `signalBackupWithdraw`. /// @dev If the trader is withdrawing after calling `signalBackupWithdraw`, /// this will reset the time to zero, writing to storage. modifier withBrokerSignatureOrSignal(address _token, bytes _signature) { address trader = msg.sender; // If a signature has been provided, verify it - otherwise, verify that // the user has signalled the withdraw if (_signature.length > 0) { require (brokerVerifierContract.verifyWithdrawSignature(trader, _signature), "invalid signature"); } else { require(traderWithdrawalSignals[trader][_token] != 0, "not signalled"); /* solium-disable-next-line security/no-block-members */ require((now - traderWithdrawalSignals[trader][_token]) > SIGNAL_DELAY, "signal time remaining"); traderWithdrawalSignals[trader][_token] = 0; } _; } /// @notice Allows the owner of the contract to update the address of the /// RenExSettlement contract. /// /// @param _newSettlementContract the address of the new settlement contract function updateRenExSettlementContract(RenExSettlement _newSettlementContract) external onlyOwner { emit LogRenExSettlementContractUpdated(settlementContract, _newSettlementContract); settlementContract = _newSettlementContract; } /// @notice Allows the owner of the contract to update the address of the /// DarknodeRewardVault contract. /// /// @param _newRewardVaultContract the address of the new reward vault contract function updateRewardVaultContract(DarknodeRewardVault _newRewardVaultContract) external onlyOwner { emit LogRewardVaultContractUpdated(rewardVaultContract, _newRewardVaultContract); rewardVaultContract = _newRewardVaultContract; } /// @notice Allows the owner of the contract to update the address of the /// RenExBrokerVerifier contract. /// /// @param _newBrokerVerifierContract the address of the new broker verifier contract function updateBrokerVerifierContract(RenExBrokerVerifier _newBrokerVerifierContract) external onlyOwner { emit LogBrokerVerifierContractUpdated(brokerVerifierContract, _newBrokerVerifierContract); brokerVerifierContract = _newBrokerVerifierContract; } /// @notice Transfer a token value from one trader to another, transferring /// a fee to the RewardVault. Can only be called by the RenExSettlement /// contract. /// /// @param _traderFrom The address of the trader to decrement the balance of. /// @param _traderTo The address of the trader to increment the balance of. /// @param _token The token's address. /// @param _value The number of tokens to decrement the balance by (in the /// token's smallest unit). /// @param _fee The fee amount to forward on to the RewardVault. /// @param _feePayee The recipient of the fee. function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee) external onlyRenExSettlementContract { require(traderBalances[_traderFrom][_token] >= _fee, "insufficient funds for fee"); if (address(_token) == ETHEREUM) { rewardVaultContract.deposit.value(_fee)(_feePayee, ERC20(_token), _fee); } else { CompatibleERC20(_token).safeApprove(rewardVaultContract, _fee); rewardVaultContract.deposit(_feePayee, ERC20(_token), _fee); } privateDecrementBalance(_traderFrom, ERC20(_token), _value + _fee); if (_value > 0) { privateIncrementBalance(_traderTo, ERC20(_token), _value); } } /// @notice Deposits ETH or an ERC20 token into the contract. /// /// @param _token The token's address (must be a registered token). /// @param _value The amount to deposit in the token's smallest unit. function deposit(ERC20 _token, uint256 _value) external payable { address trader = msg.sender; uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched value parameter and tx value"); } else { require(msg.value == 0, "unexpected ether transfer"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(trader, this, _value); } privateIncrementBalance(trader, _token, receivedValue); } /// @notice Withdraws ETH or an ERC20 token from the contract. A broker /// signature is required to guarantee that the trader has a sufficient /// balance after accounting for open orders. As a trustless backup, /// traders can withdraw 48 hours after calling `signalBackupWithdraw`. /// /// @param _token The token's address. /// @param _value The amount to withdraw in the token's smallest unit. /// @param _signature The broker signature function withdraw(ERC20 _token, uint256 _value, bytes _signature) external withBrokerSignatureOrSignal(_token, _signature) { address trader = msg.sender; privateDecrementBalance(trader, _token, _value); if (address(_token) == ETHEREUM) { trader.transfer(_value); } else { CompatibleERC20(_token).safeTransfer(trader, _value); } } /// @notice A trader can withdraw without needing a broker signature if they /// first call `signalBackupWithdraw` for the token they want to withdraw. /// The trader can only withdraw the particular token once for each call to /// this function. Traders can signal the intent to withdraw multiple /// tokens. /// Once this function is called, brokers will not sign order-opens for the /// trader until the trader has withdrawn, guaranteeing that they won't have /// orders open for the particular token. function signalBackupWithdraw(address _token) external { /* solium-disable-next-line security/no-block-members */ traderWithdrawalSignals[msg.sender][_token] = now; } function privateIncrementBalance(address _trader, ERC20 _token, uint256 _value) private { traderBalances[_trader][_token] = traderBalances[_trader][_token].add(_value); emit LogBalanceIncreased(_trader, _token, _value); } function privateDecrementBalance(address _trader, ERC20 _token, uint256 _value) private { require(traderBalances[_trader][_token] >= _value, "insufficient funds"); traderBalances[_trader][_token] = traderBalances[_trader][_token].sub(_value); emit LogBalanceDecreased(_trader, _token, _value); } }
returns the priority of the given orderID. The priority is the index of the order in the orderbook.
function orderPriority(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].priority; }
1,044,490