file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2021-06-09
*/
// Sources flattened with hardhat v2.0.11 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File contracts/interfaces/IController.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IController {
function addCK(address _ckToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isCK(address _ckToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// File contracts/interfaces/ICKToken.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
/**
* @title ICKToken
* @author Cook Finance
*
* Interface for operating with CKTokens.
*/
interface ICKToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a CKToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a CKToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
// File contracts/interfaces/IManagerIssuanceHook.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IManagerIssuanceHook {
function invokePreIssueHook(ICKToken _ckToken, uint256 _issueQuantity, address _sender, address _to) external;
function invokePreRedeemHook(ICKToken _ckToken, uint256 _redeemQuantity, address _sender, address _to) external;
}
// File contracts/protocol/lib/Invoke.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title Invoke
* @author Cook Finance
*
* A collection of common utility functions for interacting with the CKToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the CKToken to set approvals of the ERC20 token to a spender.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the CKToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ICKToken _ckToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_ckToken.invoke(_token, 0, callData);
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_ckToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
* The new CKToken balance must equal the existing balance less the quantity transferred
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the CKToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken));
Invoke.invokeTransfer(_ckToken, _token, _to, _quantity);
// Get new balance of transferred token for CKToken
uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the CKToken to unwrap the passed quantity of WETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_ckToken.invoke(_weth, 0, callData);
}
/**
* Instructs the CKToken to wrap the passed quantity of ETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_ckToken.invoke(_weth, _quantity, callData);
}
}
// File contracts/lib/AddressArrayUtils.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Cook Finance
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/lib/ExplicitERC20.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ExplicitERC20
* @author Cook Finance
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
// File contracts/interfaces/IModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Cook Finance
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a CKToken to notify that this module was removed from the CK token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File contracts/lib/PreciseUnitMath.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title PreciseUnitMath
* @author Cook Finance
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* @dev Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
// File contracts/protocol/lib/Position.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title Position
* @author Cook Finance
*
* Collection of helper functions for handling and updating CKToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the CKToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the CKToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the CKToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the CKToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ICKToken _ckToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _ckToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the CKToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _ckToken Address of CKToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ICKToken _ckToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_ckToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.removeComponent(_component);
}
}
_ckToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _ckToken CKToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ICKToken _ckToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_ckToken.isComponent(_component)) {
_ckToken.addComponent(_component);
_ckToken.addExternalPositionModule(_component, _module);
} else if (!_ckToken.isExternalPositionModule(_component, _module)) {
_ckToken.addExternalPositionModule(_component, _module);
}
_ckToken.editExternalPositionUnit(_component, _module, _newUnit);
_ckToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_ckToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _ckToken.getExternalPositionModules(_component);
if (_ckToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_ckToken.removeComponent(_component);
}
_ckToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _ckTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _ckTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _ckTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_ckTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ICKToken _ckToken, address _component) internal view returns(uint256) {
int256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component);
return _ckToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @param _ckTotalSupply Current CKToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ICKToken _ckToken,
address _component,
uint256 _ckTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_ckToken));
uint256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_ckTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_ckToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes CKToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of CKToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _ckTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_ckTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_ckTokenSupply);
}
}
// File contracts/interfaces/IIntegrationRegistry.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
// File contracts/interfaces/IPriceOracle.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Cook Finance
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
// File contracts/interfaces/ICKValuer.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface ICKValuer {
function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256);
}
// File contracts/protocol/lib/ResourceIdentifier.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ResourceIdentifier
* @author Cook Finance
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// CKValuer resource will always be resource ID 2 in the system
uint256 constant internal CK_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of CK valuer on Controller. Note: CKValuer is stored as index 2 on the Controller
*/
function getCKValuer(IController _controller) internal view returns (ICKValuer) {
return ICKValuer(_controller.resourceId(CK_VALUER_RESOURCE_ID));
}
}
// File contracts/protocol/lib/ModuleBase.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ModuleBase
* @author Cook Finance
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ICKToken;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidCK(ICKToken _ckToken) {
_validateOnlyManagerAndValidCK(_ckToken);
_;
}
modifier onlyCKManager(ICKToken _ckToken, address _caller) {
_validateOnlyCKManager(_ckToken, _caller);
_;
}
modifier onlyValidAndInitializedCK(ICKToken _ckToken) {
_validateOnlyValidAndInitializedCK(_ckToken);
_;
}
/**
* Throws if the sender is not a CKToken's module or module not enabled
*/
modifier onlyModule(ICKToken _ckToken) {
_validateOnlyModule(_ckToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the CKToken is valid
*/
modifier onlyValidAndPendingCK(ICKToken _ckToken) {
_validateOnlyValidAndPendingCK(_ckToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _ckToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromCKToken(ICKToken _ckToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_ckToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the CKToken
*/
function isCKPendingInitialization(ICKToken _ckToken) internal view returns(bool) {
return _ckToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the CKToken's manager
*/
function isCKManager(ICKToken _ckToken, address _toCheck) internal view returns(bool) {
return _ckToken.manager() == _toCheck;
}
/**
* Returns true if CKToken must be enabled on the controller
* and module is registered on the CKToken
*/
function isCKValidAndInitialized(ICKToken _ckToken) internal view returns(bool) {
return controller.isCK(address(_ckToken)) &&
_ckToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must CKToken manager and CKToken must be valid and initialized
*/
function _validateOnlyManagerAndValidCK(ICKToken _ckToken) internal view {
require(isCKManager(_ckToken, msg.sender), "Must be the CKToken manager");
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must CKToken manager
*/
function _validateOnlyCKManager(ICKToken _ckToken, address _caller) internal view {
require(isCKManager(_ckToken, _caller), "Must be the CKToken manager");
}
/**
* CKToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedCK(ICKToken _ckToken) internal view {
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ICKToken _ckToken) internal view {
require(
_ckToken.moduleStates(msg.sender) == ICKToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* CKToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view {
require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken");
require(isCKPendingInitialization(_ckToken), "Must be pending initialization");
}
}
// File contracts/protocol/modules/BasicIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title BasicIssuanceModule
* @author Cook Finance
*
* Module that enables issuance and redemption functionality on a CKToken. This is a module that is
* required to bring the totalSupply of a CK above 0.
*/
contract BasicIssuanceModule is ModuleBase, ReentrancyGuard {
using Invoke for ICKToken;
using Position for ICKToken.Position;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using SafeCast for int256;
/* ============ Events ============ */
event CKTokenIssued(
address indexed _ckToken,
address indexed _issuer,
address indexed _to,
address _hookContract,
uint256 _quantity
);
event CKTokenRedeemed(
address indexed _ckToken,
address indexed _redeemer,
address indexed _to,
uint256 _quantity
);
/* ============ State Variables ============ */
// Mapping of CKToken to Issuance hook configurations
mapping(ICKToken => IManagerIssuanceHook) public managerIssuanceHook;
/* ============ Constructor ============ */
/**
* Set state controller state variable
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public ModuleBase(_controller) {}
/* ============ External Functions ============ */
/**
* Deposits the CKToken's position components into the CKToken and mints the CKToken of the given quantity
* to the specified _to address. This function only handles Default Positions (positionState = 0).
*
* @param _ckToken Instance of the CKToken contract
* @param _quantity Quantity of the CKToken to mint
* @param _to Address to mint CKToken to
*/
function issue(
ICKToken _ckToken,
uint256 _quantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
require(_quantity > 0, "Issue quantity must be > 0");
address hookContract = _callPreIssueHooks(_ckToken, _quantity, msg.sender, _to);
(
address[] memory components,
uint256[] memory componentQuantities
) = getRequiredComponentUnitsForIssue(_ckToken, _quantity);
// For each position, transfer the required underlying to the CKToken
for (uint256 i = 0; i < components.length; i++) {
// Transfer the component to the CKToken
transferFrom(
IERC20(components[i]),
msg.sender,
address(_ckToken),
componentQuantities[i]
);
}
// Mint the CKToken
_ckToken.mint(_to, _quantity);
emit CKTokenIssued(address(_ckToken), msg.sender, _to, hookContract, _quantity);
}
/**
* Redeems the CKToken's positions and sends the components of the given
* quantity to the caller. This function only handles Default Positions (positionState = 0).
*
* @param _ckToken Instance of the CKToken contract
* @param _quantity Quantity of the CKToken to redeem
* @param _to Address to send component assets to
*/
function redeem(
ICKToken _ckToken,
uint256 _quantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
require(_quantity > 0, "Redeem quantity must be > 0");
// Burn the CKToken - ERC20's internal burn already checks that the user has enough balance
_ckToken.burn(msg.sender, _quantity);
// For each position, invoke the CKToken to transfer the tokens to the user
address[] memory components = _ckToken.getComponents();
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
require(!_ckToken.hasExternalPosition(component), "Only default positions are supported");
uint256 unit = _ckToken.getDefaultPositionRealUnit(component).toUint256();
// Use preciseMul to round down to ensure overcollateration when small redeem quantities are provided
uint256 componentQuantity = _quantity.preciseMul(unit);
// Instruct the CKToken to transfer the component to the user
_ckToken.strictInvokeTransfer(
component,
_to,
componentQuantity
);
}
emit CKTokenRedeemed(address(_ckToken), msg.sender, _to, _quantity);
}
/**
* Initializes this module to the CKToken with issuance-related hooks. Only callable by the CKToken's manager.
* Hook addresses are optional. Address(0) means that no hook will be called
*
* @param _ckToken Instance of the CKToken to issue
* @param _preIssueHook Instance of the Manager Contract with the Pre-Issuance Hook function
*/
function initialize(
ICKToken _ckToken,
IManagerIssuanceHook _preIssueHook
)
external
onlyCKManager(_ckToken, msg.sender)
onlyValidAndPendingCK(_ckToken)
{
managerIssuanceHook[_ckToken] = _preIssueHook;
_ckToken.initializeModule();
}
/**
* Reverts as this module should not be removable after added. Users should always
* have a way to redeem their CKs
*/
function removeModule() external override {
revert("The BasicIssuanceModule module cannot be removed");
}
/* ============ External Getter Functions ============ */
/**
* Retrieves the addresses and units required to mint a particular quantity of CKToken.
*
* @param _ckToken Instance of the CKToken to issue
* @param _quantity Quantity of CKToken to issue
* @return address[] List of component addresses
* @return uint256[] List of component units required to issue the quantity of CKTokens
*/
function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
)
public
view
onlyValidAndInitializedCK(_ckToken)
returns (address[] memory, uint256[] memory)
{
address[] memory components = _ckToken.getComponents();
uint256[] memory notionalUnits = new uint256[](components.length);
for (uint256 i = 0; i < components.length; i++) {
require(!_ckToken.hasExternalPosition(components[i]), "Only default positions are supported");
notionalUnits[i] = _ckToken.getDefaultPositionRealUnit(components[i]).toUint256().preciseMulCeil(_quantity);
}
return (components, notionalUnits);
}
/* ============ Internal Functions ============ */
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ICKToken _ckToken,
uint256 _quantity,
address _caller,
address _to
)
internal
returns(address)
{
IManagerIssuanceHook preIssueHook = managerIssuanceHook[_ckToken];
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_ckToken, _quantity, _caller, _to);
return address(preIssueHook);
}
return address(0);
}
} | Retrieves the addresses and units required to mint a particular quantity of CKToken. _ckToken Instance of the CKToken to issue _quantity Quantity of CKToken to issue return address[] List of component addresses return uint256[] List of component units required to issue the quantity of CKTokens/ | function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
)
public
view
onlyValidAndInitializedCK(_ckToken)
returns (address[] memory, uint256[] memory)
{
address[] memory components = _ckToken.getComponents();
uint256[] memory notionalUnits = new uint256[](components.length);
for (uint256 i = 0; i < components.length; i++) {
require(!_ckToken.hasExternalPosition(components[i]), "Only default positions are supported");
notionalUnits[i] = _ckToken.getDefaultPositionRealUnit(components[i]).toUint256().preciseMulCeil(_quantity);
}
return (components, notionalUnits);
}
| 2,097,662 |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ITheSpace.sol";
import "./ITheSpaceRegistry.sol";
contract TheSpaceRegistry is ITheSpaceRegistry, ERC721Enumerable, Ownable {
/**
* @dev Total possible number of ERC721 token
*/
uint256 private _totalSupply;
/**
* @dev ERC20 token used as currency
*/
ERC20 public immutable currency;
/**
* @dev Record for all tokens (tokenId => TokenRecord).
*/
mapping(uint256 => TokenRecord) public tokenRecord;
/**
* @dev Color of each token.
*/
mapping(uint256 => uint256) public pixelColor;
/**
* @dev Tax configuration of market.
*/
mapping(ConfigOptions => uint256) public taxConfig;
/**
* @dev Global state of tax and treasury.
*/
TreasuryRecord public treasuryRecord;
/**
* @dev Create Property contract, setup attached currency contract, setup tax rate.
*/
constructor(
string memory propertyName_,
string memory propertySymbol_,
uint256 totalSupply_,
uint256 taxRate_,
uint256 treasuryShare_,
uint256 mintTax_,
address currencyAddress_
) ERC721(propertyName_, propertySymbol_) {
// initialize total supply
_totalSupply = totalSupply_;
// initialize currency contract
currency = ERC20(currencyAddress_);
// initialize tax config
taxConfig[ConfigOptions.taxRate] = taxRate_;
emit Config(ConfigOptions.taxRate, taxRate_);
taxConfig[ConfigOptions.treasuryShare] = treasuryShare_;
emit Config(ConfigOptions.treasuryShare, treasuryShare_);
taxConfig[ConfigOptions.mintTax] = mintTax_;
emit Config(ConfigOptions.mintTax, mintTax_);
}
//////////////////////////////
/// Getters & Setters
//////////////////////////////
/**
* @notice See {IERC20-totalSupply}.
* @dev Always return total possible amount of supply, instead of current token in circulation.
*/
function totalSupply() public view override(ERC721Enumerable, IERC721Enumerable) returns (uint256) {
return _totalSupply;
}
//////////////////////////////
/// Setters for global variables
//////////////////////////////
/// @inheritdoc ITheSpaceRegistry
function setTotalSupply(uint256 totalSupply_) external onlyOwner {
emit TotalSupply(_totalSupply, totalSupply_);
_totalSupply = totalSupply_;
}
/// @inheritdoc ITheSpaceRegistry
function setTaxConfig(ConfigOptions option_, uint256 value_) external onlyOwner {
taxConfig[option_] = value_;
emit Config(option_, value_);
}
/// @inheritdoc ITheSpaceRegistry
function setTreasuryRecord(
uint256 accumulatedUBI_,
uint256 accumulatedTreasury_,
uint256 treasuryWithdrawn_
) external onlyOwner {
treasuryRecord = TreasuryRecord(accumulatedUBI_, accumulatedTreasury_, treasuryWithdrawn_);
}
/// @inheritdoc ITheSpaceRegistry
function setTokenRecord(
uint256 tokenId_,
uint256 price_,
uint256 lastTaxCollection_,
uint256 ubiWithdrawn_
) external onlyOwner {
tokenRecord[tokenId_] = TokenRecord(price_, lastTaxCollection_, ubiWithdrawn_);
}
/// @inheritdoc ITheSpaceRegistry
function setColor(
uint256 tokenId_,
uint256 color_,
address owner_
) external onlyOwner {
pixelColor[tokenId_] = color_;
emit Color(tokenId_, color_, owner_);
}
//////////////////////////////
/// Event emission
//////////////////////////////
/// @inheritdoc ITheSpaceRegistry
function emitTax(
uint256 tokenId_,
address taxpayer_,
uint256 amount_
) external onlyOwner {
emit Tax(tokenId_, taxpayer_, amount_);
}
/// @inheritdoc ITheSpaceRegistry
function emitPrice(
uint256 tokenId_,
uint256 price_,
address operator_
) external onlyOwner {
emit Price(tokenId_, price_, operator_);
}
/// @inheritdoc ITheSpaceRegistry
function emitUBI(
uint256 tokenId_,
address recipient_,
uint256 amount_
) external onlyOwner {
emit UBI(tokenId_, recipient_, amount_);
}
/// @inheritdoc ITheSpaceRegistry
function emitTreasury(address recipient_, uint256 amount_) external onlyOwner {
emit Treasury(recipient_, amount_);
}
/// @inheritdoc ITheSpaceRegistry
function emitDeal(
uint256 tokenId_,
address from_,
address to_,
uint256 amount_
) external onlyOwner {
emit Deal(tokenId_, from_, to_, amount_);
}
//////////////////////////////
/// ERC721 property related
//////////////////////////////
/// @inheritdoc ITheSpaceRegistry
function mint(address to_, uint256 tokenId_) external onlyOwner {
if (tokenId_ > _totalSupply || tokenId_ < 1) revert InvalidTokenId(1, _totalSupply);
_safeMint(to_, tokenId_);
}
/// @inheritdoc ITheSpaceRegistry
function burn(uint256 tokenId_) external onlyOwner {
_burn(tokenId_);
}
/// @inheritdoc ITheSpaceRegistry
function safeTransferByMarket(
address from_,
address to_,
uint256 tokenId_
) external onlyOwner {
_safeTransfer(from_, to_, tokenId_, "");
}
/// @inheritdoc ITheSpaceRegistry
function exists(uint256 tokenId_) external view returns (bool) {
return _exists(tokenId_);
}
/// @inheritdoc ITheSpaceRegistry
function isApprovedOrOwner(address spender_, uint256 tokenId_) external view returns (bool) {
return _isApprovedOrOwner(spender_, tokenId_);
}
/**
* @notice See {IERC721-transferFrom}.
* @dev Override to collect tax and set price before transfer.
*/
function transferFrom(
address from_,
address to_,
uint256 tokenId_
) public override(ERC721, IERC721) {
safeTransferFrom(from_, to_, tokenId_, "");
}
/**
* @notice See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) public override(ERC721, IERC721) {
// solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved");
ITheSpace market = ITheSpace(owner());
bool success = market._beforeTransferByRegistry(tokenId_);
if (success) {
_safeTransfer(from_, to_, tokenId_, data_);
}
}
/**
* @notice See {IERC721-tokenURI}.
*/
function tokenURI(uint256 tokenId_) public view override returns (string memory uri) {
ITheSpace market = ITheSpace(owner());
uri = market._tokenURI(tokenId_);
}
//////////////////////////////
/// ERC20 currency related
//////////////////////////////
/// @inheritdoc ITheSpaceRegistry
function transferCurrency(address to_, uint256 amount_) external onlyOwner {
currency.transfer(to_, amount_);
}
/// @inheritdoc ITheSpaceRegistry
function transferCurrencyFrom(
address from_,
address to_,
uint256 amount_
) external onlyOwner {
currency.transferFrom(from_, to_, amount_);
}
}
| See {IERC721-safeTransferFrom}./ solhint-disable-next-line max-line-length | function safeTransferFrom(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) public override(ERC721, IERC721) {
require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved");
ITheSpace market = ITheSpace(owner());
bool success = market._beforeTransferByRegistry(tokenId_);
if (success) {
_safeTransfer(from_, to_, tokenId_, data_);
}
}
| 12,728,661 |
./partial_match/3/0xFBa39B68AE1C0E112698cB0a1FBDa7fa1280D5cF/sources/MasterChef.sol | Safe chm transfer function, just in case if rounding error causes pool to not have enough CHMs. | function safeChmTransfer(address _to, uint256 _amount) internal {
uint256 chmBal = chm.balanceOf(address(this));
if (_amount > chmBal) {
chm.transfer(_to, chmBal);
chm.transfer(_to, _amount);
}
}
| 5,283,710 |
// SPDX-License-Identifier: AGPL-3.0
// ©2022 Ponderware Ltd
pragma solidity ^0.8.12;
import "./openzeppelin/contracts/utils/introspection/IERC165.sol";
import "./openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "./openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IQuest3Data {
function getDeath (uint256 seed, uint256 prevLevel, bytes[8] memory stats) external view returns (bytes memory death, string memory ending);
function getFail (uint256 seed, uint256 level, bytes[8] memory stats) external view returns (bytes memory happening);
function getAdvance (uint256 seed, uint256 level, bytes[8] memory stats) external view returns (bytes memory happening, bytes memory stat);
function getMetadata (uint256 tokenId, uint256 level, uint8 journeyLength, bytes[15] memory storySegments, bytes[8] memory stats, uint16 heroStatus) external pure returns (string memory);
function generateCompletionImage (uint tokenId, uint level, bytes memory lastWords, uint heroStatus) external pure returns (bytes memory);
function generateProgressImage (uint tokenId, uint level) external pure returns (bytes memory);
}
/**
* @title Quest3
* @author Ponderware Ltd (a.k.a. Pondertech Digital Solutions)
* @notice ERC-721 Quest Tokens (where will your journey lead?)
* @dev ERC-721 Enumerable Token with fully-on-chain ERC721 Metadata
*/
contract Quest3 is IERC721Enumerable, IERC721Metadata {
string public name = "Quest-3";
string public symbol = unicode"⛰";
uint256 public maxSupply = 25600;
uint256 public totalSupply = 0;
address public contractOwner;
address[25600] internal Owners; // Maps tokenIds to owning addresses.
mapping (address => uint256[]) internal TokensByOwner; // Mapping from address to owned tokens.
uint16[25600] internal OwnerTokenIndex; // Maps the a tokenId to its index in the `TokensByOwner[address]` array.
mapping(uint256 => address) internal TokenApprovals; // Mapping from token ID to approved address.
mapping(address => mapping(address => bool)) internal OperatorApprovals; // Mapping from owner to operator approvals.
bool paused = true; // Pausing stops all user interactions.
bool frozen = false; // Freezing stops minting and actions.
uint256 public MintPriceWei = 0.01994206980085 ether;
/**
* @dev Contains the journey information for the token. Idx 0 is the journey length, Idx [1..14] contains the reveal seed at level of the token at that journey position, and Idx 15 is a flag to indicate if an action is in the `ActionQueue`.
*/
mapping (uint256 => uint16[16]) TokenHistory;
/**
* @dev The number of items a token must reveal to increase their hero status.
*/
uint256 public HeroThreshold = 10;
/**
* @dev If a token reveals more than HeroThreshold actions, the number of reveals is added to that token's hero status.
*/
uint16[25600] public HeroStatus;
/**
* @dev Reference to the metadata assembly contract.
*/
IQuest3Data Data;
// Owner Functions
constructor (address quest3DataContract) {
contractOwner = msg.sender;
Data = IQuest3Data(quest3DataContract);
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender);
}
/**
* @dev Change the owner of the contract.
*/
function transferOwnership (address newOwner) public onlyOwner {
contractOwner = newOwner;
}
function pause () public onlyOwner {
paused = true;
}
function unpause () public onlyOwner {
paused = false;
}
function ownerWithdraw () public {
payable(contractOwner).transfer(address(this).balance);
}
function clearPendingStatus (uint256 tokenId) public onlyOwner {
TokenHistory[tokenId][IS_PENDING_INDEX] = 0;
}
function setHeroThreshold (uint256 threshold) public onlyOwner {
HeroThreshold = threshold;
}
/**
* @dev Set `maxSupply` to `totalSupply` to end minting.
*/
function permanentlyCloseMint() public onlyOwner {
maxSupply = totalSupply;
}
/**
* @dev When frozen action (and mint) calls will throw.
*/
function setFrozen (bool state) public onlyOwner {
frozen = state;
}
// Modifiers
modifier onlyOwner() {
require(msg.sender == contractOwner, "Not Owner");
_;
}
modifier whenNotPaused() {
require(paused == false || msg.sender == contractOwner, "Paused");
_;
}
// Action Queue
/**
* @dev Actions are placed into the FIFO `ActionQueue` ring and revealed on future blocks.
*/
Action[256] public ActionQueue;
uint constant public MAX_QUEUE = 256;
/**
* @dev Actions are queued. The `revealBlock` is the block at which this action becomes eligible for reveal.
*/
struct Action {
uint128 revealBlock;
uint128 tokenId;
}
/**
* @dev `count` is the current length of the queue. `index` is the offset to the first queue item.
*/
struct QueueCursor {
uint16 index;
uint16 count;
}
QueueCursor public Cursor = QueueCursor(0,0);
function getQueueLength () public view returns (uint256) {
return Cursor.count;
}
/**
* @dev Assembles the `ActionQueue` into an array of actions in order (deconstructs the "ring").
*/
function getQueue () public view returns (Action[] memory) {
uint count = Cursor.count;
uint index = Cursor.index;
Action[] memory queue = new Action[](count);
for (uint i = 0; i < queue.length; i++) {
queue[i] = ActionQueue[index];
index++;
if(index == MAX_QUEUE) index = 0;
}
return queue;
}
// Quest Actions / Progress Handling
/**
* @dev Indexes into `TokenHistory` arrays. The seed/level data is stored in indexes [1..14].
*/
uint256 constant JOURNEY_LENGTH_INDEX = 0;
uint256 constant IS_PENDING_INDEX = 15;
/**
* @dev Reveals the most recent pending action on a token. Packs the result into [seed (12 bits), level (4 bits)].
*/
function updateTokenHistory (uint256 tokenId) internal {
uint16[16] storage history = TokenHistory[tokenId];
uint journeyLength = history[JOURNEY_LENGTH_INDEX];
uint level = history[journeyLength] & 15;
uint prevLevel = 0;
if (journeyLength == 0) {
level = 1; // starting level
} else if (journeyLength == 1) {
prevLevel = 1; // starting level is always 1
} else {
prevLevel = history[journeyLength - 1] & 15; // prevLevel is penultimate level in pendingHistory
}
uint nextSeed = uint256(keccak256(abi.encodePacked(tokenId, blockhash(block.number-1))));
uint resolution = nextSeed & 255;
uint deathThreshold = 5 + level * 9;
uint failThreshold = 90 + level * 22;
if (level == 1) { deathThreshold = 2; } // low chance to die on level 1
if (prevLevel == level) { failThreshold = 0; } // must die or advance
if (resolution < deathThreshold) {
level = 0; // died
} else if (resolution >= failThreshold) {
level = level + 1; // advanced
}
history[JOURNEY_LENGTH_INDEX] = uint16(journeyLength + 1);
history[journeyLength + 1] = uint16((nextSeed << 4) + level);
history[IS_PENDING_INDEX] = 0;
}
/**
* @dev Reveals up to `maxReveals` pending `Action`s in the Action Queue, then enqueues the supplied `tokenId` if eligible.
*/
function handleAction (uint256 tokenId, uint256 maxReveals) private whenNotPaused {
require(frozen == false, "Frozen");
uint count = Cursor.count;
uint index = Cursor.index;
if (maxReveals < 3) {
maxReveals = 3;
}
uint revealCount = 0;
for (uint i = 0; i < maxReveals; i++) {
if (count == 0) break;
Action storage action = ActionQueue[index];
if (block.number <= action.revealBlock) break;
updateTokenHistory(action.tokenId);
delete ActionQueue[index];
count--;
index++;
revealCount++;
if(index == MAX_QUEUE) index = 0;
}
if (revealCount >= HeroThreshold) {
HeroStatus[tokenId] += uint16(revealCount);
}
uint16[16] storage history = TokenHistory[tokenId];
uint tokenJourneyLength = history[JOURNEY_LENGTH_INDEX];
uint tokenLevel = history[tokenJourneyLength] & 15;
if (((tokenLevel > 0 && tokenLevel < 8) || tokenJourneyLength == 0)
&& count < MAX_QUEUE
&& history[IS_PENDING_INDEX] == 0)
{
uint tokenQueueIndex = count + index;
count++;
if (MAX_QUEUE <= tokenQueueIndex) {
tokenQueueIndex -= MAX_QUEUE;
}
ActionQueue[tokenQueueIndex] = Action(uint128(block.number + 1), uint128(tokenId));
history[IS_PENDING_INDEX] = 1;
}
Cursor.count = uint16(count);
Cursor.index = uint16(index);
}
/**
* @notice Like `doSomething` but set a max number of reveals to perform (must be >= HeroThreshold). If it reveals enough, the number of reveals will be added to the tokens HeroScore. Can be called even if your quest is complete.
* @dev Cannot be called by a smart contract.
*/
function doSomethingHeroic (uint256 tokenId, uint256 maxAssists) public {
require(msg.sender == Owners[tokenId] && msg.sender == tx.origin, "Not Owner");
require(maxAssists >= HeroThreshold, "A true hero must assist many others");
handleAction(tokenId, maxAssists);
}
/**
* @notice Places the token into the `ActionQueue` where it will be revealed by actions in future blocks. Reveals up to 3 pending actions.
* @dev Cannot be called by a smart contract.
*/
function doSomething (uint256 tokenId) public {
require(msg.sender == Owners[tokenId] && msg.sender == tx.origin, "Not Owner");
handleAction(tokenId, 3);
}
/**
* @notice Like `doSomething` but allows multiple tokenIds to be put in the ActionQueue.
* @dev Cannot be called by a smart contract.
*/
function doSomething (uint256[] memory tokenIds) public {
require(msg.sender == tx.origin);
for (uint i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(msg.sender == Owners[tokenId], "Not Owner");
handleAction(tokenId, 3);
}
}
// Minting
/**
* @dev Bookkeeping for minting. Note: minting does not guarantee entry into the `ActionQueue`.
*/
function mintHelper (address recipient) private {
uint256 tokenId = totalSupply;
TokensByOwner[recipient].push(tokenId);
OwnerTokenIndex[tokenId] = uint16(TokensByOwner[recipient].length);
Owners[tokenId] = recipient;
totalSupply++;
handleAction(tokenId, 3);
emit Transfer(address(0), recipient, tokenId);
}
/**
* @notice Mint tokens to the provided recipient address, quantity per call is limited to 10.
*/
function mint (address recipient, uint256 quantity) public payable whenNotPaused {
require (quantity <= 10, "Quantity Limit Exceeded");
require (totalSupply + quantity <= maxSupply, "Max Supply Exceeded");
uint256 cost = quantity * MintPriceWei;
require(msg.value >= cost, "Insufficent Funds");
for (uint i = 0; i < quantity; i++) {
mintHelper(recipient);
}
}
/**
* @notice Mint tokens to msg.sender, quantity per call is limited to 10.
*/
function mint (uint256 quantity) public payable {
mint(msg.sender, quantity);
}
/**
* @notice Mint tokens to an array of recipient addresses, array length must be <= 10.
*/
function mint (address[] memory recipients) public payable whenNotPaused {
uint quantity = recipients.length;
require (quantity <= 10 || msg.sender == contractOwner, "Quantity Limit Exceeded");
require (totalSupply + quantity <= maxSupply, "Max Supply Exceeded");
uint256 cost = quantity * MintPriceWei;
require(msg.value >= cost, "Insufficent Funds");
for (uint i = 0; i < quantity; i++) {
mintHelper(recipients[i]);
}
}
// Quest Info
/**
* @notice Shows where the token is in the `Action Queue`.
* @dev `pending` indicates the token is in the queue. `position` is the number of preceding Actions. `revealBlock` is the block at which the action becomes eligible for reveal.
*/
function isPending (uint256 tokenId) public view returns (bool pending, uint position, uint revealBlock) {
pending = TokenHistory[tokenId][IS_PENDING_INDEX] == 1;
if (pending) {
uint count = Cursor.count;
uint index = Cursor.index;
for (uint i = 0; i < count; i++) {
Action storage action = ActionQueue[index];
if (action.tokenId == tokenId) {
position = i;
revealBlock = action.revealBlock;
break;
}
index++;
if(index == MAX_QUEUE) index = 0;
}
}
}
/**
* @notice Fetches details used to generate token metadata. `level` => indicates numeric stage of the quest. `journeyLength` => number of revealed actions. `storySegments` => text corresponding to each reveled action. `stats` => attributes collected on the quest. `heroStatus` => number of tokens revealed through `doSomethingHeroic`.
* @dev `level` will be in range [0(ngmi)..8(gmi)]. `storySegments` will have `journeyLength` entries unless `level` == 0 in which case it will have one additional element. `stats` indexes correspond to levels - 1.
*/
function getDetails (uint256 tokenId) public view returns (uint256 level,
uint8 journeyLength,
bytes[15] memory storySegments,
bytes[8] memory stats,
uint16 heroStatus)
{
require(tokenId < totalSupply, "Doesn't Exist");
uint16[16] storage tokenHistory = TokenHistory[tokenId];
journeyLength = uint8(tokenHistory[JOURNEY_LENGTH_INDEX]);
level = 1; // if quest has just begun, level will be 1
uint prevLevel = 1;
for (uint i = 1; i <= journeyLength; i++) {
uint256 seed = uint256(keccak256(abi.encodePacked(tokenHistory[i], tokenId)));
level = tokenHistory[i] & 15;
if (level == 0) {
(bytes memory storySegment, string memory ending) = Data.getDeath(seed, prevLevel, stats);
stats[7] = storySegment;
storySegments[i-1] = storySegment;
storySegments[i] = bytes(ending);
} else if (prevLevel == level) {
storySegments[i-1] = Data.getFail(seed, level, stats);
} else {
(bytes memory storySegment, bytes memory stat) = Data.getAdvance(seed, level, stats);
stats[level - 1] = stat;
storySegments[i-1] = storySegment;
}
prevLevel = level;
}
heroStatus = HeroStatus[tokenId];
if (tokenHistory[IS_PENDING_INDEX] == 1) {
stats[0] = "Pending";
} else if (level == 0) {
stats[0] = "NGMI";
} else if (level == 8) {
stats[0] = "GMI";
} else {
stats[0] = "Questing";
}
}
/**
* @notice Fetches the current stage of the journey in numeric terms. 0 => NGMI. 8 => GMI.
* @dev `level` is always in the range [0..8].
*/
function getLevel (uint256 tokenId) public view returns (uint256 level) {
require(tokenId < totalSupply, "Doesn't Exist");
uint16[16] storage tokenHistory = TokenHistory[tokenId];
uint16 journeyLength = tokenHistory[JOURNEY_LENGTH_INDEX];
if (journeyLength == 0) {
return 1;
} else {
return (tokenHistory[journeyLength] & 15);
}
}
function getSym(int seed) internal pure returns (uint8) {
if (seed & 1 == 0) return 0;
if ((seed >> 1) & 1 == 0) {
return 1;
}
return 2;
}
/**
* @dev `cartouche` is an array of chevron positions and orientations. 0 => None, 1 => Right, 2 => Left. Data is only valid if `level` == 8.
*/
function getMysteriousCartouche (uint256 tokenId) public view returns (uint8 level, uint8[6] memory cartouche) {
(uint256 currentLevel,uint8 journeyLength,, bytes[8] memory stats,) = getDetails(tokenId);
if (currentLevel == 8) {
int seed = int(uint256(keccak256(abi.encodePacked(tokenId, stats[7]))) >> 141);
cartouche[0] = getSym(seed);
cartouche[1] = getSym(seed >> 2);
cartouche[2] = getSym(seed >> 4);
cartouche[3] = getSym(seed >> 6);
cartouche[4] = getSym(seed >> 8);
cartouche[5] = getSym(seed >> 10);
}
if (journeyLength > 0) {
level = uint8(currentLevel);
} else {
level = 1;
}
}
// ERC-721 Metadata
/**
* @notice Assembles and returns the Base64 encoded token URI containing the JSON token's metadata. Assembled entirely on-chain.
*/
function tokenURI (uint256 tokenId) public view returns (string memory) {
(uint256 level, uint8 journeyLength, bytes[15] memory storySegments, bytes[8] memory stats, uint16 heroStatus) = getDetails(tokenId);
return Data.getMetadata(tokenId, level, journeyLength, storySegments, stats, heroStatus);
}
/**
* @notice Assembles and returns the token's SVG image. Assembled entirely on-chain.
*/
function tokenSVG (uint256 tokenId) public view returns (string memory svg) {
(uint256 level, uint8 journeyLength,, bytes[8] memory stats, uint16 heroStatus) = getDetails(tokenId);
if (journeyLength > 0 && (level == 0 || level == 8)) {
svg = string(Data.generateCompletionImage(tokenId, level, stats[7], heroStatus));
} else {
svg = string(Data.generateProgressImage(tokenId, level));
}
}
// ERC-721 Base
function tokenExists(uint256 tokenId) public view returns (bool) {
return (tokenId < totalSupply);
}
function ownerOf(uint256 tokenId) public view returns (address) {
require(tokenExists(tokenId), "ERC721: Nonexistent token");
return Owners[tokenId];
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return TokensByOwner[owner].length;
}
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
return
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId;
}
function _approve(address to, uint256 tokenId) internal {
TokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(tokenId < totalSupply, "ERC721: approved query for nonexistent token");
return TokenApprovals[tokenId];
}
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return OperatorApprovals[owner][operator];
}
function setApprovalForAll(
address operator,
bool approved
) external virtual {
require(msg.sender != operator, "ERC721: approve to caller");
OperatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (isContract(to)) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _transfer(
address from,
address to,
uint256 tokenId
) private whenNotPaused {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_approve(address(0), tokenId);
uint16 valueIndex = OwnerTokenIndex[tokenId];
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = TokensByOwner[from].length - 1;
if (lastIndex != toDeleteIndex) {
uint256 lastTokenId = TokensByOwner[from][lastIndex];
TokensByOwner[from][toDeleteIndex] = lastTokenId;
OwnerTokenIndex[lastTokenId] = valueIndex;
}
TokensByOwner[from].pop();
TokensByOwner[to].push(tokenId);
OwnerTokenIndex[tokenId] = uint16(TokensByOwner[to].length);
Owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(tokenId < totalSupply, "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
// Enumerable
function tokenByIndex(uint256 tokenId) public view returns (uint256) {
require(tokenExists(tokenId), "Nonexistent Token");
return tokenId;
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return TokensByOwner[owner][index];
}
// Rescuers
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20(address tokenContract) public onlyOwner {
IERC20 token = IERC20(tokenContract);
token.transfer(contractOwner, token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner {
IERC721(tokenContract).safeTransferFrom(address(this), contractOwner, tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | Fetches details used to generate token metadata. `level` => indicates numeric stage of the quest. `journeyLength` => number of revealed actions. `storySegments` => text corresponding to each reveled action. `stats` => attributes collected on the quest. `heroStatus` => number of tokens revealed through `doSomethingHeroic`. `level` will be in range [0(ngmi)..8(gmi)]. `storySegments` will have `journeyLength` entries unless `level` == 0 in which case it will have one additional element. `stats` indexes correspond to levels - 1./ | function getDetails (uint256 tokenId) public view returns (uint256 level,
uint8 journeyLength,
bytes[15] memory storySegments,
bytes[8] memory stats,
uint16 heroStatus)
{
require(tokenId < totalSupply, "Doesn't Exist");
uint16[16] storage tokenHistory = TokenHistory[tokenId];
journeyLength = uint8(tokenHistory[JOURNEY_LENGTH_INDEX]);
uint prevLevel = 1;
for (uint i = 1; i <= journeyLength; i++) {
uint256 seed = uint256(keccak256(abi.encodePacked(tokenHistory[i], tokenId)));
level = tokenHistory[i] & 15;
if (level == 0) {
(bytes memory storySegment, string memory ending) = Data.getDeath(seed, prevLevel, stats);
stats[7] = storySegment;
storySegments[i-1] = storySegment;
storySegments[i] = bytes(ending);
storySegments[i-1] = Data.getFail(seed, level, stats);
(bytes memory storySegment, bytes memory stat) = Data.getAdvance(seed, level, stats);
stats[level - 1] = stat;
storySegments[i-1] = storySegment;
}
prevLevel = level;
}
heroStatus = HeroStatus[tokenId];
if (tokenHistory[IS_PENDING_INDEX] == 1) {
stats[0] = "Pending";
stats[0] = "NGMI";
stats[0] = "GMI";
stats[0] = "Questing";
}
}
| 10,334,685 |
./full_match/1/0x86A53C9E32Abd3677e38BD0b390f24dD080E6426/sources/browser/coinbase.sol | function approve(address spender, uint value) external returns (bool); | interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function balanceOf(address owner) external view returns (uint);
}
| 9,820,850 |
./partial_match/42/0x75C1b8cD9CFD01Df29196Db4786236Ad740E0A6f/sources/DisposableMemberRoles.sol | Allows selling of NXM for ether. Seller first needs to give this contract allowance to transfer/burn tokens in the NXMToken contract _amount Amount of NXM to sell return success returns true on successfull sale/ | function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns (bool success) {
require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance");
require(!tf.isLockedForMemberVote(msg.sender), "Member voted");
require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit");
uint sellingPrice = _getWei(_amount);
tc.burnFrom(msg.sender, _amount);
msg.sender.transfer(sellingPrice);
success = true;
}
| 3,325,838 |
/*
Copyright (C) 2015 Thomas Bertani - Oraclize srl
*/
// https://www.oraclize.it/service/api
contract OraclizeI {
function query(uint timestamp, byte[] formula_1, byte[] formula_2, byte[] formula_3, byte[] formula_4){}
function query(uint timestamp, address param, byte[] formula_1, byte[] formula_2, byte[] formula_3, byte[] formula_4){}
}
contract Insurance {
// logging helper
event Log(uint k);
address[5] public users_list;
uint public users_list_length;
mapping (address => uint) public users_balance;
address[5] public investors_list;
uint public investors_list_length;
mapping (address => uint) public investors_invested;
// just a function to send the funds back to the sending address, another option would be to STOP execution by throwing an exception here
function RETURN(){
msg.sender.send(msg.value);
}
// FALLBACK function
function(){
if (msg.sender == address(0x26588a9301b0428d95e6fc3a5024fce8bec12d51)) callback();
}
// registers a new user
function register(byte[] formula_1a, byte[] flight_number, byte[] formula_3a, byte[] formula_4a, byte[] formula_4b, uint arrivaltime){
if (uint(msg.value) == 0) return; // you didn't send us any money
if (now > arrivaltime-2*24*3600){ RETURN(); return; } // refuse new insurances if arrivaltime < 2d from now
if (users_list_length > 4){ RETURN(); return; } // supporting max 5 users for now
if (users_balance[msg.sender] > 0){ RETURN(); return; } // don't register twice!
uint balance_busy = 0;
for (uint k=0; k<users_list_length; k++){
balance_busy += 5*users_balance[users_list[k]];
}
if (uint(address(this).balance)-balance_busy < 5*uint(msg.value)){ RETURN(); return; } // don't have enough funds to cover your insurance
// ORACLIZE CALL
OraclizeI oracle = OraclizeI(0x393519c01e80b188d326d461e4639bc0e3f62af0);
oracle.query(arrivaltime+3*3600, msg.sender, formula_1a, flight_number, formula_3a, formula_4a);
uint160 sender_b = uint160(msg.sender);
oracle.query(arrivaltime+3*3600, address(++sender_b), formula_1a, flight_number, formula_3a, formula_4b);
//
delete users_balance[msg.sender];
users_balance[msg.sender] = msg.value;
users_list[users_list_length] = msg.sender;
users_list_length++;
}
// Oraclize callback
function callback(){
uint160 sender_;
for (uint j=0; j<20; j++){
sender_ *= 256;
sender_ += uint160(msg.data[j]);
}
address sender = address(sender_);
uint sender_b_ = uint160(sender);
sender_b_--;
address sender_b = address(sender_b_);
uint status = 0;
if (users_balance[sender_b] > 0){ // status = 1
status = 1;
uint balance = users_balance[sender_b];
delete users_balance[sender_b];
} else {
delete users_balance[sender];
}
if ((users_balance[sender_b] > 0)&&(status == 1)) sender.send(balance*5);
for (uint k=0; k<users_list_length; k++){
if ((users_list[k] == sender)||(users_list[k] == sender_b)){
users_list[k] = 0x0;
}
}
}
// invest new funds
function invest() {
if (investors_invested[msg.sender] == 0){
investors_list[investors_list_length] = msg.sender;
investors_list_length++;
}
investors_invested[msg.sender] += uint(msg.value);
}
// deinvest funds
function deinvest(){
if (investors_invested[msg.sender] == 0) return;
uint balance_busy = 0;
for (uint k=0; k<users_list_length; k++){
balance_busy += 5*users_balance[users_list[k]];
}
uint invested_total = 0;
for (k=0; k<investors_list_length; k++){
invested_total += investors_invested[investors_list[k]];
}
uint gain = investors_invested[msg.sender] / invested_total * (uint(address(this).balance) - balance_busy);
if (gain > uint(address(this).balance)-balance_busy) return; // do not let the investor deinvest in the case it is busy
msg.sender.send(gain);
investors_invested[msg.sender] = 0;
for (k=0; k<investors_list_length; k++){
if (investors_list[k] == msg.sender) investors_list[k] = 0x0;
}
}
// get the current user insured amount
function get() returns (uint){
return users_balance[msg.sender];
}
// get a specific user insured amount
function get_user(address user) returns (uint){
return users_balance[user];
}
// returns percentage performance data about this investment
function investment_ratio() returns (uint){
uint insured_customers_funds = 0;
for (uint k=0; k<users_list_length; k++){
insured_customers_funds += users_balance[users_list[k]];
}
uint invested_total = 0;
for (k=0; k<investors_list_length; k++){
invested_total += investors_invested[investors_list[k]];
}
uint ratio = 100 * ((uint(address(this).balance) - insured_customers_funds)/invested_total);
return ratio;
}
}
| registers a new user | function register(byte[] formula_1a, byte[] flight_number, byte[] formula_3a, byte[] formula_4a, byte[] formula_4b, uint arrivaltime){
uint balance_busy = 0;
for (uint k=0; k<users_list_length; k++){
balance_busy += 5*users_balance[users_list[k]];
}
oracle.query(arrivaltime+3*3600, msg.sender, formula_1a, flight_number, formula_3a, formula_4a);
uint160 sender_b = uint160(msg.sender);
oracle.query(arrivaltime+3*3600, address(++sender_b), formula_1a, flight_number, formula_3a, formula_4b);
users_balance[msg.sender] = msg.value;
users_list[users_list_length] = msg.sender;
users_list_length++;
}
| 12,703,586 |
./partial_match/1/0x69E4bf938FB99D765dAEc594Ed2b16A00D16EaaA/sources/TypicalTigersMigration.sol | See {IERC721-approve}./ | function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
| 3,658,585 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./spec_interfaces/ICommittee.sol";
import "./ManagedContract.sol";
import "./spec_interfaces/IStakingRewards.sol";
import "./spec_interfaces/IFeesAndBootstrapRewards.sol";
/// @title Committee contract
contract Committee is ICommittee, ManagedContract {
using SafeMath for uint256;
using SafeMath for uint96;
uint96 constant CERTIFICATION_MASK = 1 << 95;
uint96 constant WEIGHT_MASK = ~CERTIFICATION_MASK;
struct CommitteeMember {
address addr;
uint96 weightAndCertifiedBit;
}
CommitteeMember[] committee;
struct MemberStatus {
uint32 pos;
bool inCommittee;
}
mapping(address => MemberStatus) public membersStatus;
struct CommitteeStats {
uint96 totalWeight;
uint32 generalCommitteeSize;
uint32 certifiedCommitteeSize;
}
CommitteeStats committeeStats;
uint8 maxCommitteeSize;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
/// @param _maxCommitteeSize is the maximum number of committee members
constructor(IContractRegistry _contractRegistry, address _registryAdmin, uint8 _maxCommitteeSize) ManagedContract(_contractRegistry, _registryAdmin) public {
setMaxCommitteeSize(_maxCommitteeSize);
}
modifier onlyElectionsContract() {
require(msg.sender == electionsContract, "caller is not the elections");
_;
}
/*
* External functions
*/
/// Notifies a weight change of a member
/// @dev Called only by: Elections contract
/// @param addr is the committee member address
/// @param weight is the updated weight of the committee member
function memberWeightChange(address addr, uint256 weight) external override onlyElectionsContract onlyWhenActive {
MemberStatus memory status = membersStatus[addr];
if (!status.inCommittee) {
return;
}
CommitteeMember memory member = committee[status.pos];
(uint prevWeight, bool isCertified) = getWeightCertification(member);
committeeStats.totalWeight = uint96(committeeStats.totalWeight.sub(prevWeight).add(weight));
committee[status.pos].weightAndCertifiedBit = packWeightCertification(weight, isCertified);
emit CommitteeChange(addr, weight, isCertified, true);
}
/// Notifies a change in the certification of a member
/// @dev Called only by: Elections contract
/// @param addr is the committee member address
/// @param isCertified is the updated certification state of the member
function memberCertificationChange(address addr, bool isCertified) external override onlyElectionsContract onlyWhenActive {
MemberStatus memory status = membersStatus[addr];
if (!status.inCommittee) {
return;
}
CommitteeMember memory member = committee[status.pos];
(uint weight, bool prevCertification) = getWeightCertification(member);
CommitteeStats memory _committeeStats = committeeStats;
feesAndBootstrapRewardsContract.committeeMembershipWillChange(addr, true, prevCertification, isCertified, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize);
committeeStats.certifiedCommitteeSize = _committeeStats.certifiedCommitteeSize - (prevCertification ? 1 : 0) + (isCertified ? 1 : 0);
committee[status.pos].weightAndCertifiedBit = packWeightCertification(weight, isCertified);
emit CommitteeChange(addr, weight, isCertified, true);
}
/// Notifies a member removal for example due to voteOut or voteUnready
/// @dev Called only by: Elections contract
/// @param memberRemoved is the removed committee member address
/// @return memberRemoved indicates whether the member was removed from the committee
/// @return removedMemberWeight indicates the removed member weight
/// @return removedMemberCertified indicates whether the member was in the certified committee
function removeMember(address addr) external override onlyElectionsContract onlyWhenActive returns (bool memberRemoved, uint removedMemberWeight, bool removedMemberCertified) {
MemberStatus memory status = membersStatus[addr];
if (!status.inCommittee) {
return (false, 0, false);
}
memberRemoved = true;
(removedMemberWeight, removedMemberCertified) = getWeightCertification(committee[status.pos]);
committeeStats = removeMemberAtPos(status.pos, true, committeeStats);
}
/// Notifies a new member applicable for committee (due to registration, unbanning, certification change)
/// The new member will be added only if it is qualified to join the committee
/// @dev Called only by: Elections contract
/// @param addr is the added committee member address
/// @param weight is the added member weight
/// @param isCertified is the added member certification state
/// @return memberAdded bool indicates whether the member was added
function addMember(address addr, uint256 weight, bool isCertified) external override onlyElectionsContract onlyWhenActive returns (bool memberAdded) {
return _addMember(addr, weight, isCertified, true);
}
/// Checks if addMember() would add a the member to the committee (qualified to join)
/// @param addr is the candidate committee member address
/// @param weight is the candidate committee member weight
/// @return wouldAddMember bool indicates whether the member will be added
function checkAddMember(address addr, uint256 weight) external view override returns (bool wouldAddMember) {
if (membersStatus[addr].inCommittee) {
return false;
}
(bool qualified, ) = qualifiesToEnterCommittee(addr, weight, maxCommitteeSize);
return qualified;
}
/// Returns the committee members and their weights
/// @return addrs is the committee members list
/// @return weights is an array of uint, indicating committee members list weight
/// @return certification is an array of bool, indicating the committee members certification status
function getCommittee() external override view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification) {
return _getCommittee();
}
/// Returns the currently appointed committee data
/// @return generalCommitteeSize is the number of members in the committee
/// @return certifiedCommitteeSize is the number of certified members in the committee
/// @return totalWeight is the total effective stake (weight) of the committee
function getCommitteeStats() external override view returns (uint generalCommitteeSize, uint certifiedCommitteeSize, uint totalWeight) {
CommitteeStats memory _committeeStats = committeeStats;
return (_committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize, _committeeStats.totalWeight);
}
/// Returns a committee member data
/// @param addr is the committee member address
/// @return inCommittee indicates whether the queried address is a member in the committee
/// @return weight is the committee member weight
/// @return isCertified indicates whether the committee member is certified
/// @return totalCommitteeWeight is the total weight of the committee.
function getMemberInfo(address addr) external override view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight) {
MemberStatus memory status = membersStatus[addr];
inCommittee = status.inCommittee;
if (inCommittee) {
(weight, isCertified) = getWeightCertification(committee[status.pos]);
}
totalCommitteeWeight = committeeStats.totalWeight;
}
/// Emits a CommitteeSnapshot events with current committee info
/// @dev a CommitteeSnapshot is useful on contract migration or to remove the need to track past events.
function emitCommitteeSnapshot() external override {
(address[] memory addrs, uint256[] memory weights, bool[] memory certification) = _getCommittee();
for (uint i = 0; i < addrs.length; i++) {
emit CommitteeChange(addrs[i], weights[i], certification[i], true);
}
emit CommitteeSnapshot(addrs, weights, certification);
}
/*
* Governance functions
*/
/// Sets the maximum number of committee members
/// @dev governance function called only by the functional manager
/// @dev when reducing the number of members, the bottom ones are removed from the committee
/// @param _maxCommitteeSize is the maximum number of committee members
function setMaxCommitteeSize(uint8 _maxCommitteeSize) public override onlyFunctionalManager {
uint8 prevMaxCommitteeSize = maxCommitteeSize;
maxCommitteeSize = _maxCommitteeSize;
while (committee.length > _maxCommitteeSize) {
(, ,uint pos) = _getMinCommitteeMember();
committeeStats = removeMemberAtPos(pos, true, committeeStats);
}
emit MaxCommitteeSizeChanged(_maxCommitteeSize, prevMaxCommitteeSize);
}
/// Returns the maximum number of committee members
/// @return maxCommitteeSize is the maximum number of committee members
function getMaxCommitteeSize() external override view returns (uint8) {
return maxCommitteeSize;
}
/// Imports the committee members from a previous committee contract during migration
/// @dev initialization function called only by the initializationManager
/// @dev does not update the reward contract to avoid incorrect notifications
/// @param previousCommitteeContract is the address of the previous committee contract
function importMembers(ICommittee previousCommitteeContract) external override onlyInitializationAdmin {
(address[] memory addrs, uint256[] memory weights, bool[] memory certification) = previousCommitteeContract.getCommittee();
for (uint i = 0; i < addrs.length; i++) {
_addMember(addrs[i], weights[i], certification[i], false);
}
}
/*
* Private
*/
/// Checks a member eligibility to join the committee and add if eligible
/// @dev Private function called by AddMember and importMembers
/// @dev checks if the maximum committee size has reached, removes the lowest weight member if needed
/// @param addr is the added committee member address
/// @param weight is the added member weight
/// @param isCertified is the added member certification state
/// @param notifyRewards indicates whether to notify the rewards contract on the update, false on members import during migration
function _addMember(address addr, uint256 weight, bool isCertified, bool notifyRewards) private returns (bool memberAdded) {
MemberStatus memory status = membersStatus[addr];
if (status.inCommittee) {
return false;
}
(bool qualified, uint entryPos) = qualifiesToEnterCommittee(addr, weight, maxCommitteeSize);
if (!qualified) {
return false;
}
memberAdded = true;
CommitteeStats memory _committeeStats = committeeStats;
if (notifyRewards) {
stakingRewardsContract.committeeMembershipWillChange(addr, weight, _committeeStats.totalWeight, false, true);
feesAndBootstrapRewardsContract.committeeMembershipWillChange(addr, false, isCertified, isCertified, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize);
}
_committeeStats.generalCommitteeSize++;
if (isCertified) _committeeStats.certifiedCommitteeSize++;
_committeeStats.totalWeight = uint96(_committeeStats.totalWeight.add(weight));
CommitteeMember memory newMember = CommitteeMember({
addr: addr,
weightAndCertifiedBit: packWeightCertification(weight, isCertified)
});
if (entryPos < committee.length) {
CommitteeMember memory removed = committee[entryPos];
unpackWeightCertification(removed.weightAndCertifiedBit);
_committeeStats = removeMemberAtPos(entryPos, false, _committeeStats);
committee[entryPos] = newMember;
} else {
committee.push(newMember);
}
status.inCommittee = true;
status.pos = uint32(entryPos);
membersStatus[addr] = status;
committeeStats = _committeeStats;
emit CommitteeChange(addr, weight, isCertified, true);
}
/// Pack a member's weight and certification to a compact uint96 representation
function packWeightCertification(uint256 weight, bool certification) private pure returns (uint96 weightAndCertified) {
return uint96(weight) | (certification ? CERTIFICATION_MASK : 0);
}
/// Unpacks a compact uint96 representation to a member's weight and certification
function unpackWeightCertification(uint96 weightAndCertifiedBit) private pure returns (uint256 weight, bool certification) {
return (uint256(weightAndCertifiedBit & WEIGHT_MASK), weightAndCertifiedBit & CERTIFICATION_MASK != 0);
}
/// Returns the weight and certification of a CommitteeMember entry
function getWeightCertification(CommitteeMember memory member) private pure returns (uint256 weight, bool certification) {
return unpackWeightCertification(member.weightAndCertifiedBit);
}
/// Returns the committee members and their weights
/// @dev Private function called by getCommittee and emitCommitteeSnapshot
/// @return addrs is the committee members list
/// @return weights is an array of uint, indicating committee members list weight
/// @return certification is an array of bool, indicating the committee members certification status
function _getCommittee() private view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification) {
CommitteeMember[] memory _committee = committee;
addrs = new address[](_committee.length);
weights = new uint[](_committee.length);
certification = new bool[](_committee.length);
for (uint i = 0; i < _committee.length; i++) {
addrs[i] = _committee[i].addr;
(weights[i], certification[i]) = getWeightCertification(_committee[i]);
}
}
/// Returns the committee member with the minimum weight as a candidate to be removed from the committee
/// @dev Private function called by qualifiesToEnterCommittee and setMaxCommitteeSize
/// @return minMemberAddress is the address of the committee member with the minimum weight
/// @return minMemberWeight is the weight of the committee member with the minimum weight
/// @return minMemberPos is the committee array pos of the committee member with the minimum weight
function _getMinCommitteeMember() private view returns (
address minMemberAddress,
uint256 minMemberWeight,
uint minMemberPos
){
CommitteeMember[] memory _committee = committee;
minMemberPos = uint256(-1);
minMemberWeight = uint256(-1);
uint256 memberWeight;
address memberAddress;
for (uint i = 0; i < _committee.length; i++) {
memberAddress = _committee[i].addr;
(memberWeight,) = getWeightCertification(_committee[i]);
if (memberWeight < minMemberWeight || memberWeight == minMemberWeight && memberAddress < minMemberAddress) {
minMemberPos = i;
minMemberWeight = memberWeight;
minMemberAddress = memberAddress;
}
}
}
/// Checks if a potential candidate is qualified to join the committee
/// @dev Private function called by checkAddMember and _addMember
/// @param addr is the candidate committee member address
/// @param weight is the candidate committee member weight
/// @param _maxCommitteeSize is the maximum number of committee members
/// @return qualified indicates whether the candidate committee member qualifies to join
/// @return entryPos is the committee array pos allocated to the member (empty or the position of the minimum weight member)
function qualifiesToEnterCommittee(address addr, uint256 weight, uint8 _maxCommitteeSize) private view returns (bool qualified, uint entryPos) {
uint committeeLength = committee.length;
if (committeeLength < _maxCommitteeSize) {
return (true, committeeLength);
}
(address minMemberAddress, uint256 minMemberWeight, uint minMemberPos) = _getMinCommitteeMember();
if (weight > minMemberWeight || weight == minMemberWeight && addr > minMemberAddress) {
return (true, minMemberPos);
}
return (false, 0);
}
/// Removes a member at a certain pos in the committee array
/// @dev Private function called by _addMember, removeMember and setMaxCommitteeSize
/// @param pos is the committee array pos to be removed
/// @param clearFromList indicates whether to clear the entry in the committee array, false when overriding it with a new member
/// @param _committeeStats is the current committee statistics
/// @return newCommitteeStats is the updated committee committee statistics after the removal
function removeMemberAtPos(uint pos, bool clearFromList, CommitteeStats memory _committeeStats) private returns (CommitteeStats memory newCommitteeStats){
CommitteeMember memory member = committee[pos];
(uint weight, bool certification) = getWeightCertification(member);
stakingRewardsContract.committeeMembershipWillChange(member.addr, weight, _committeeStats.totalWeight, true, false);
feesAndBootstrapRewardsContract.committeeMembershipWillChange(member.addr, true, certification, certification, _committeeStats.generalCommitteeSize, _committeeStats.certifiedCommitteeSize);
delete membersStatus[member.addr];
_committeeStats.generalCommitteeSize--;
if (certification) _committeeStats.certifiedCommitteeSize--;
_committeeStats.totalWeight = uint96(_committeeStats.totalWeight.sub(weight));
emit CommitteeChange(member.addr, weight, certification, false);
if (clearFromList) {
uint committeeLength = committee.length;
if (pos < committeeLength - 1) {
CommitteeMember memory last = committee[committeeLength - 1];
committee[pos] = last;
membersStatus[last.addr].pos = uint32(pos);
}
committee.pop();
}
return _committeeStats;
}
/*
* Contracts topology / registry interface
*/
address electionsContract;
IStakingRewards stakingRewardsContract;
IFeesAndBootstrapRewards feesAndBootstrapRewardsContract;
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external override {
electionsContract = getElectionsContract();
stakingRewardsContract = IStakingRewards(getStakingRewardsContract());
feesAndBootstrapRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract());
}
}
| Imports the committee members from a previous committee contract during migration initialization function called only by the initializationManager does not update the reward contract to avoid incorrect notifications previousCommitteeContract is the address of the previous committee contract | function importMembers(ICommittee previousCommitteeContract) external override onlyInitializationAdmin {
(address[] memory addrs, uint256[] memory weights, bool[] memory certification) = previousCommitteeContract.getCommittee();
for (uint i = 0; i < addrs.length; i++) {
_addMember(addrs[i], weights[i], certification[i], false);
}
}
| 2,521,355 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// Implements account locking. The main goal of this design is to allow
/// unlocking of multiple accounts in O(1). To achieve this we keep a list of
/// locks per account. Every time an account is locked or unlocked, this list is
/// checked for inactive locks, which are subsequently removed. To ensure that
/// this operation does not become too expensive in gas costs, a maximum amount
/// of active locks per account is enforced.
contract AccountLocks {
uint256 public constant MAX_LOCKS_PER_ACCOUNT = 128;
mapping(bytes32 => Lock) private locks;
mapping(address => Account) private accounts;
/// Creates a lock that can be used to lock accounts. The id needs to be
/// unique and collision resistant. The expiry time is given in unix time.
function _createLock(bytes32 id, uint256 expiry) internal {
require(locks[id].owner == address(0), "Lock already exists");
locks[id] = Lock(msg.sender, expiry, false);
}
/// Attaches a lock to an account. Only when the lock is unlocked or expires
/// can the account be unlocked again.
/// Calling this function triggers a cleanup of inactive locks, making this
/// an O(N) operation, where N = MAX_LOCKS_PER_ACCOUNT.
function _lock(address account, bytes32 lockId) internal {
require(locks[lockId].owner != address(0), "Lock does not exist");
bytes32[] storage accountLocks = accounts[account].locks;
removeInactiveLocks(accountLocks);
require(accountLocks.length < MAX_LOCKS_PER_ACCOUNT, "Max locks reached");
accountLocks.push(lockId);
}
/// Unlocks a lock, thereby freeing any accounts that are attached to this
/// lock. This is an O(1) operation. Only the party that created the lock is
/// allowed to unlock it.
function _unlock(bytes32 lockId) internal {
Lock storage lock = locks[lockId];
require(lock.owner != address(0), "Lock does not exist");
require(lock.owner == msg.sender, "Only lock creator can unlock");
lock.unlocked = true;
}
/// Unlocks an account. This will fail if there are any active locks attached
/// to this account.
/// Calling this function triggers a cleanup of inactive locks, making this
/// an O(N) operation, where N = MAX_LOCKS_PER_ACCOUNT.
function _unlockAccount() internal {
bytes32[] storage accountLocks = accounts[msg.sender].locks;
removeInactiveLocks(accountLocks);
require(accountLocks.length == 0, "Account locked");
}
function removeInactiveLocks(bytes32[] storage lockIds) private {
uint256 index = 0;
while (true) {
if (index >= lockIds.length) {
return;
}
if (isInactive(locks[lockIds[index]])) {
lockIds[index] = lockIds[lockIds.length - 1];
lockIds.pop();
} else {
index++;
}
}
}
function isInactive(Lock storage lock) private view returns (bool) {
return lock.unlocked || lock.expiry <= block.timestamp;
}
struct Lock {
address owner;
uint256 expiry;
bool unlocked;
}
struct Account {
bytes32[] locks;
}
}
| Unlocks an account. This will fail if there are any active locks attached to this account. Calling this function triggers a cleanup of inactive locks, making this an O(N) operation, where N = MAX_LOCKS_PER_ACCOUNT. | function _unlockAccount() internal {
bytes32[] storage accountLocks = accounts[msg.sender].locks;
removeInactiveLocks(accountLocks);
require(accountLocks.length == 0, "Account locked");
}
| 978,808 |
/*
.&&&&&&&&&&&%
&&&&&&&&&&&&&
&&&&&&&&&&&&&
%%%&&&&&&&&&%
%%%%%%%%%%%%%%%%%%%%%%
./(((((((### %%%%%%%%%%%%%%%%&((((
///((((((((## #%%%%%%%%%%%%%%%
////((((((((# ####%%%%%%%%%%%%
/////(((((((( #######%#%%%%%%%
///////(((((((((######################
...........(((((((#######,,,,,,,,,,,
.... ... *((((((((((##
************* ,/(((((((((((/
************* ,/////(((((((((((((/ .((((((((((((
************* ,///(((((((((/ ((((((((((((
************************* ///////////(/ ((((((//////
.************************. ///////////// ,/////////////
*******************. +/////////////////////////////////
*******************. +++///////////////////
*************************, **********************
.,,,,,,,,,,,,,******************************************************
*****************************************************
****************************, ************
************* **********************, ************
************* **********************, ************
********************************************************. ............
*********************************************************
*********************************************************
********************************************
********************************************
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import './ERC2981Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/ERC1155PausableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
/**
* @dev {ERC1155} token, including:
*
* - a voucher minter role that allows for token minting (creation) with voucher
* - a voucher transfer role that allows for token transfering with voucher
* - a pauser role that allows to stop all token transfers
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter, transfer, and pauser
* roles, as well as the default admin role, which will let it grant minter,
* transfer and pauser roles to other accounts.
*/
contract CoralNFT is
Initializable,
ContextUpgradeable,
AccessControlEnumerableUpgradeable,
ERC2981Upgradeable,
ERC1155Upgradeable,
ERC1155PausableUpgradeable,
EIP712Upgradeable,
ReentrancyGuardUpgradeable
{
function initialize(
string calldata baseUri,
address admin,
address voucherMinter,
address voucherTransferer,
address pauser
) external virtual initializer {
__CoralNFT_init(
baseUri,
admin,
voucherMinter,
voucherTransferer,
pauser
);
}
string public constant name = 'Coral';
string public constant symbol = 'CORAL';
string public constant version = '1';
uint64 public constant MAXIMUM_ROYALTY_BPS = 2000;
bytes32 public constant VOUCHER_MINTER_ROLE =
keccak256('VOUCHER_MINTER_ROLE');
bytes32 public constant VOUCHER_TRANSFER_ROLE =
keccak256('VOUCHER_TRANSFER_ROLE');
bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE');
bytes32 private constant _MINT_TYPE_HASH =
keccak256(
'MintAndTransferVoucher(uint256 tokenID,uint256 amount,address creator,uint256 expirationTime,uint128 royaltyBPS,string uri)'
);
bytes32 private constant _TRANSFER_TYPE_HASH =
keccak256(
'TransferVoucher(uint256 tokenID,address owner,uint256 expirationTime,uint256 amount,uint256 nonce)'
);
/// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function.
struct MintAndTransferVoucher {
/// @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert.
uint256 tokenID;
uint256 amount;
/// @notice The address of creator of this token - the voucher requires that it is signed by with this address.
address creator;
/// @notice Transfer voucher can be used until it has reach expiration timestamp.
uint256 expirationTime;
/// @notice The percentage of sale amount that will be belong to the royalty owner.
uint128 royaltyBPS;
/// @notice The metadata URI to associate with this token.
string uri;
}
/// @notice Represents a permit to transfer NFT on behave of token owner. A signed transfer voucher can be used only by voucher transfer role for a limited of time.
struct TransferVoucher {
uint256 tokenID;
/// @notice The address of owner of this token - the voucher requires that it is signed by with this address.
address owner;
/// @notice Transfer voucher can be used until it has reach expiration timestamp.
uint256 expirationTime;
/// @notice Limited tranfered amount that can use this voucher to transfer
uint256 amount;
/// @notice nonce
uint256 nonce;
}
// Optional mapping for token URIs
mapping(uint256 => string) internal _tokenURIs;
mapping(uint256 => uint256) internal _tokenAmounts;
mapping(uint256 => uint256) internal _transferAmounts;
event MintVoucherGasUsage(
address indexed from,
address indexed to,
uint256 id,
uint256 remainingGas
);
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
function __CoralNFT_init(
string calldata baseUri,
address admin,
address voucherMinter,
address voucherTransferer,
address pauser
) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__ERC1155_init_unchained(baseUri);
__Pausable_init_unchained();
__ERC1155Pausable_init_unchained();
__ERC1155PresetMinterPauser_init_unchained(
admin,
voucherMinter,
voucherTransferer,
pauser
);
__EIP712_init_unchained(name, version);
__ReentrancyGuard_init_unchained();
__ERC2981_init_unchained();
}
function __ERC1155PresetMinterPauser_init_unchained(
address admin,
address voucherMinter,
address voucherTransferer,
address pauser
) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(VOUCHER_MINTER_ROLE, voucherMinter);
_setupRole(VOUCHER_TRANSFER_ROLE, voucherTransferer);
_setupRole(PAUSER_ROLE, pauser);
}
/// @notice Returns the chain id of the current blockchain.
/// @dev This is used to workaround an issue with ganache returning different values from the on-chain chainid() function and
/// the eth_chainId RPC method. See https://github.com/protocol/nft-website/issues/121 for context.
function getChainID() external view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
function _timeNow() internal view returns (uint256) {
return block.timestamp;
}
function _exists(uint256 tokenID) internal view returns (bool) {
return _tokenAmounts[tokenID] > 0;
}
function _setTokenURI(uint256 tokenID, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenID),
'ERC721Metadata: URI set of nonexistent token.'
);
_tokenURIs[tokenID] = _tokenURI;
}
function tokenAmount(uint256 tokenID) public view returns (uint256) {
return _tokenAmounts[tokenID];
}
function uri(uint256 tokenID)
public
view
virtual
override
returns (string memory)
{
return
string(
abi.encodePacked(
ERC1155Upgradeable.uri(tokenID),
_tokenURIs[tokenID]
)
);
}
function transferVoucher(
address to,
uint256 transferAmount,
TransferVoucher calldata voucher,
bytes calldata signature
) external nonReentrant {
require(
to != address(0),
'Burning a token is not allowed with voucher.'
);
require(voucher.expirationTime > _timeNow(), 'Voucher is expired.');
require(_exists(voucher.tokenID), 'Token ID does not exist.');
require(
hasRole(VOUCHER_TRANSFER_ROLE, _msgSender()),
'Only an address with transfer role can transfer Token with Voucher.'
);
address signer = _verifyTransferVoucher(voucher, signature);
require(
signer == voucher.owner,
'Signer is not the same as owner for this Token.'
);
uint256 ownAmount = balanceOf(voucher.owner, voucher.tokenID);
require(
ownAmount >= transferAmount,
'Owner does not have enough token to transfer.'
);
uint256 voucherID = uint256(
keccak256(
abi.encode(
voucher.tokenID,
voucher.owner,
voucher.expirationTime,
voucher.nonce
)
)
);
uint256 currentTranferAmount = _transferAmounts[voucherID];
require(
voucher.amount >= currentTranferAmount + transferAmount,
'The transfer voucher has reached the limit of transfer amount.'
);
_transferAmounts[voucherID] = currentTranferAmount + transferAmount;
_safeTransferFrom(
voucher.owner,
to,
voucher.tokenID,
transferAmount,
''
);
}
function mintAndTransferVoucher(
address to,
uint256 transferAmount,
MintAndTransferVoucher calldata voucher,
bytes calldata signature
) external returns (uint256) {
require(
voucher.amount >= transferAmount,
'Amount of Token is lower than transfer amount.'
);
require(voucher.expirationTime > _timeNow(), 'Voucher is expired.');
require(
(voucher.tokenID & 0xffffffffffffffffffff) ==
uint256(uint160(voucher.creator)) / 2**80,
'Token ID is not under address space of the creator.'
);
require(
hasRole(VOUCHER_MINTER_ROLE, _msgSender()),
'Only an address with minter role can mint Token with Voucher.'
);
require(
voucher.royaltyBPS <= MAXIMUM_ROYALTY_BPS,
'Maximum basis points of royalty is 2000.'
);
address signer = _verifyMintVoucher(voucher, signature);
require(
signer == voucher.creator,
'Signer is not the same as creator for this Token.'
);
require(
!_exists(voucher.tokenID),
'Token ID has already been created.'
);
_setRoyaltyInfo(
voucher.creator,
voucher.tokenID,
1,
voucher.royaltyBPS
);
_mint(voucher.creator, voucher.tokenID, voucher.amount, '');
_setTokenURI(voucher.tokenID, voucher.uri);
emit MintVoucherGasUsage(
voucher.creator,
to,
voucher.tokenID,
gasleft()
);
if (to != address(0) && transferAmount > 0) {
_safeTransferFrom(
voucher.creator,
to,
voucher.tokenID,
transferAmount,
''
);
}
return voucher.tokenID;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual override {
_tokenAmounts[id] = amount;
ERC1155Upgradeable._mint(account, id, amount, data);
}
function _verifyMintVoucher(
MintAndTransferVoucher calldata voucher,
bytes calldata signature
) internal view returns (address) {
bytes32 digest = _hashMintAndTransferVoucher(voucher);
return ECDSA.recover(digest, signature);
}
function _verifyTransferVoucher(
TransferVoucher calldata voucher,
bytes calldata signature
) internal view returns (address) {
bytes32 digest = _hashTransferVoucher(voucher);
return ECDSA.recover(digest, signature);
}
function _hashMintAndTransferVoucher(
MintAndTransferVoucher calldata voucher
) internal view returns (bytes32) {
return
_hashTypedDataV4(
keccak256(
abi.encode(
_MINT_TYPE_HASH,
voucher.tokenID,
voucher.amount,
voucher.creator,
voucher.expirationTime,
voucher.royaltyBPS,
keccak256(bytes(voucher.uri))
)
)
);
}
function _hashTransferVoucher(TransferVoucher calldata voucher)
internal
view
returns (bytes32)
{
return
_hashTypedDataV4(
keccak256(
abi.encode(
_TRANSFER_TYPE_HASH,
voucher.tokenID,
voucher.owner,
voucher.expirationTime,
voucher.amount,
voucher.nonce
)
)
);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
'ERC1155PresetMinterPauser: must have pauser role to pause'
);
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
'ERC1155PresetMinterPauser: must have pauser role to unpause'
);
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC2981Upgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
override(ERC1155Upgradeable, ERC1155PausableUpgradeable)
{
ERC1155PausableUpgradeable._beforeTokenTransfer(
operator,
from,
to,
ids,
amounts,
data
);
}
function revokeRole(bytes32 role, address account) public virtual override {
require(
role != DEFAULT_ADMIN_ROLE ||
(role == DEFAULT_ADMIN_ROLE &&
AccessControlEnumerableUpgradeable.getRoleMemberCount(
DEFAULT_ADMIN_ROLE
) >
1),
'Cannot revoke the only admin role account.'
);
super.revokeRole(role, account);
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
require(
role != DEFAULT_ADMIN_ROLE ||
(role == DEFAULT_ADMIN_ROLE &&
AccessControlEnumerableUpgradeable.getRoleMemberCount(
DEFAULT_ADMIN_ROLE
) >
1),
'Cannot renounce the only admin role account.'
);
super.renounceRole(role, account);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol';
import './IERC2981Upgradeable.sol';
contract ERC2981Upgradeable is
Initializable,
IERC2981Upgradeable,
ContextUpgradeable
{
struct RoyaltyInfo {
address receiver;
address candidateOwner;
uint64 feeType;
uint128 value;
}
event TransferRoyaltyOwnership(
address indexed from,
address indexed to,
uint256 id
);
mapping(uint256 => RoyaltyInfo) internal _royalties;
function __ERC2981_init() internal initializer {}
function __ERC2981_init_unchained() internal initializer {}
function _setRoyaltyInfo(
address receiver,
uint256 tokenID,
uint64 feeType,
uint128 value
) internal virtual {
_royalties[tokenID] = RoyaltyInfo(receiver, address(0), feeType, value);
}
function royaltyInfo(uint256 tokenID, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalty = _royalties[tokenID];
return (royalty.receiver, (salePrice * royalty.value) / 10000);
}
function royaltyByTokenID(uint256 _tokenID)
external
view
returns (
address,
uint64,
uint128
)
{
RoyaltyInfo memory royalty = _royalties[_tokenID];
return (royalty.receiver, royalty.feeType, royalty.value);
}
function transferRoyaltyOwnership(address candidateOwner, uint256 tokenID)
external
{
require(
_msgSender() == _royalties[tokenID].receiver,
'ERC2981: caller is not a royalty receiver.'
);
require(
candidateOwner != address(0),
'ERC2981: cannot transfer roalty ownership to the zero address.'
);
_royalties[tokenID].candidateOwner = candidateOwner;
}
function claimRoyaltyOwnership(uint256 tokenID) external {
require(
_msgSender() == _royalties[tokenID].candidateOwner,
'ERC2981: transaction submitter is not the candidate owner.'
);
address oldOwner = _royalties[tokenID].receiver;
_royalties[tokenID].receiver = _royalties[tokenID].candidateOwner;
_royalties[tokenID].candidateOwner = address(0);
emit TransferRoyaltyOwnership(
oldOwner,
_royalties[tokenID].receiver,
tokenID
);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC1155Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155PausableUpgradeable is Initializable, ERC1155Upgradeable, PausableUpgradeable {
function __ERC1155Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC1155Pausable_init_unchained();
}
function __ERC1155Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol';
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981Upgradeable {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view 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 ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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);
}
} | See {IERC165-supportsInterface}./ | function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC2981Upgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
| 229,943 |
./full_match/1/0x4E0528b9478C9A90B84F80fF771f6e4Cf07920F5/sources/browser/atomic.sol | makes a trade from token to Ether, sends Ether to msg sender token Src token srcAmount amount of src tokens minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. return amount of actual dest tokens | function swapTokenToEther(address token, uint srcAmount, uint minConversionRate) public returns (uint) {}
| 3,014,086 |
./partial_match/1/0x04487444B2d3AdF07f4B8F55Dae9ff27C94a5AFd/sources/Verdun.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Verdun", "$V") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 0;
uint256 _earlySellLiquidityFee = 4;
uint256 _earlySellMarketingFee = 2;
uint256 _earlySellDevFee = 2;
uint256 totalSupply = 1 * 10 ** 9 * 10 ** decimals();
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,548,093 |
./partial_match/42220/0xe55C3eb4a04F93c3302A5d8058348157561BF5ca/sources/home/obernardovieira/Documentos/GitHub/impact-market/smart-contracts/contracts/Community.sol | Allow community managers to unlock community claims./ | function unlock() external onlyManagers {
locked = false;
emit CommunityUnlocked(msg.sender);
}
| 3,497,806 |
./full_match/1/0x509f9725a83b5Ef9A9868e419adC7Ab7A78c0eC2/sources/src/sellers/DiamondExhibitionSeller.sol | Convenience function for inheriting sellers. Purchases tokens of given project IDs free-of-charge./ | function _purchase(address to, uint8[] memory projectIds) internal {
_purchase(
to, uint64(projectIds.length), /* total cost */ 0, DiamondExhibitionLib.encodePurchaseData(projectIds)
);
}
| 8,454,734 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {
IUniswapV3MintCallback
} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import {
IUniswapV3SwapCallback
} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import {ArrakisVaultV1Storage} from "./abstract/ArrakisVaultV1Storage.sol";
import {TickMath} from "./vendor/uniswap/TickMath.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {
FullMath,
LiquidityAmounts
} from "./vendor/uniswap/LiquidityAmounts.sol";
contract ArrakisVaultV1 is
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
ArrakisVaultV1Storage
{
using SafeERC20 for IERC20;
using TickMath for int24;
event Minted(
address receiver,
uint256 mintAmount,
uint256 amount0In,
uint256 amount1In,
uint128 liquidityMinted
);
event Burned(
address receiver,
uint256 burnAmount,
uint256 amount0Out,
uint256 amount1Out,
uint128 liquidityBurned
);
event Rebalance(
int24 lowerTick_,
int24 upperTick_,
uint128 liquidityBefore,
uint128 liquidityAfter
);
event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
// solhint-disable-next-line max-line-length
constructor(address payable _gelato, address _arrakisTreasury)
ArrakisVaultV1Storage(_gelato, _arrakisTreasury)
{} // solhint-disable-line no-empty-blocks
/// @notice Uniswap V3 callback fn, called back on pool.mint
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata /*_data*/
) external override {
require(msg.sender == address(pool), "callback caller");
if (amount0Owed > 0) token0.safeTransfer(msg.sender, amount0Owed);
if (amount1Owed > 0) token1.safeTransfer(msg.sender, amount1Owed);
}
/// @notice Uniswap v3 callback fn, called back on pool.swap
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata /*data*/
) external override {
require(msg.sender == address(pool), "callback caller");
if (amount0Delta > 0)
token0.safeTransfer(msg.sender, uint256(amount0Delta));
else if (amount1Delta > 0)
token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
// User functions => Should be called via a Router
/// @notice mint ArrakisVaultV1 Shares, fractional shares of a Uniswap V3 position/strategy
/// @dev to compute the amouint of tokens necessary to mint `mintAmount` see getMintAmounts
/// @param mintAmount The number of shares to mint
/// @param receiver The account to receive the minted shares
/// @return amount0 amount of token0 transferred from msg.sender to mint `mintAmount`
/// @return amount1 amount of token1 transferred from msg.sender to mint `mintAmount`
/// @return liquidityMinted amount of liquidity added to the underlying Uniswap V3 position
// solhint-disable-next-line function-max-lines, code-complexity
function mint(uint256 mintAmount, address receiver)
external
nonReentrant
returns (
uint256 amount0,
uint256 amount1,
uint128 liquidityMinted
)
{
require(mintAmount > 0, "mint 0");
require(
restrictedMintToggle != 11111 || msg.sender == _manager,
"restricted"
);
uint256 totalSupply = totalSupply();
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
if (totalSupply > 0) {
(uint256 amount0Current, uint256 amount1Current) =
getUnderlyingBalances();
amount0 = FullMath.mulDivRoundingUp(
amount0Current,
mintAmount,
totalSupply
);
amount1 = FullMath.mulDivRoundingUp(
amount1Current,
mintAmount,
totalSupply
);
} else {
// if supply is 0 mintAmount == liquidity to deposit
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
SafeCast.toUint128(mintAmount)
);
}
// transfer amounts owed to contract
if (amount0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), amount0);
}
if (amount1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), amount1);
}
// deposit as much new liquidity as possible
liquidityMinted = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0,
amount1
);
pool.mint(address(this), lowerTick, upperTick, liquidityMinted, "");
_mint(receiver, mintAmount);
emit Minted(receiver, mintAmount, amount0, amount1, liquidityMinted);
}
/// @notice burn ArrakisVaultV1 Shares (shares of a Uniswap V3 position) and receive underlying
/// @param burnAmount The number of shares to burn
/// @param receiver The account to receive the underlying amounts of token0 and token1
/// @return amount0 amount of token0 transferred to receiver for burning `burnAmount`
/// @return amount1 amount of token1 transferred to receiver for burning `burnAmount`
/// @return liquidityBurned amount of liquidity removed from the underlying Uniswap V3 position
// solhint-disable-next-line function-max-lines
function burn(uint256 burnAmount, address receiver)
external
nonReentrant
returns (
uint256 amount0,
uint256 amount1,
uint128 liquidityBurned
)
{
require(burnAmount > 0, "burn 0");
uint256 totalSupply = totalSupply();
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
_burn(msg.sender, burnAmount);
uint256 liquidityBurned_ =
FullMath.mulDiv(burnAmount, liquidity, totalSupply);
liquidityBurned = SafeCast.toUint128(liquidityBurned_);
(uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) =
_withdraw(lowerTick, upperTick, liquidityBurned);
_applyFees(fee0, fee1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
emit FeesEarned(fee0, fee1);
amount0 =
burn0 +
FullMath.mulDiv(
token0.balanceOf(address(this)) -
burn0 -
managerBalance0 -
arrakisBalance0,
burnAmount,
totalSupply
);
amount1 =
burn1 +
FullMath.mulDiv(
token1.balanceOf(address(this)) -
burn1 -
managerBalance1 -
arrakisBalance1,
burnAmount,
totalSupply
);
if (amount0 > 0) {
token0.safeTransfer(receiver, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(receiver, amount1);
}
emit Burned(receiver, burnAmount, amount0, amount1, liquidityBurned);
}
// Manager Functions => Called by Pool Manager
/// @notice Change the range of underlying UniswapV3 position, only manager can call
/// @dev When changing the range the inventory of token0 and token1 may be rebalanced
/// with a swap to deposit as much liquidity as possible into the new position. Swap parameters
/// can be computed by simulating the whole operation: remove all liquidity, deposit as much
/// as possible into new position, then observe how much of token0 or token1 is leftover.
/// Swap a proportion of this leftover to deposit more liquidity into the position, since
/// any leftover will be unused and sit idle until the next rebalance.
/// @param newLowerTick The new lower bound of the position's range
/// @param newUpperTick The new upper bound of the position's range
/// @param swapThresholdPrice slippage parameter on the swap as a max or min sqrtPriceX96
/// @param swapAmountBPS amount of token to swap as proportion of total. Pass 0 to ignore swap.
/// @param zeroForOne Which token to input into the swap (true = token0, false = token1)
// solhint-disable-next-line function-max-lines
function executiveRebalance(
int24 newLowerTick,
int24 newUpperTick,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) external onlyManager {
uint128 liquidity;
uint128 newLiquidity;
if (totalSupply() > 0) {
(liquidity, , , , ) = pool.positions(_getPositionID());
if (liquidity > 0) {
(, , uint256 fee0, uint256 fee1) =
_withdraw(lowerTick, upperTick, liquidity);
_applyFees(fee0, fee1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
emit FeesEarned(fee0, fee1);
}
lowerTick = newLowerTick;
upperTick = newUpperTick;
uint256 reinvest0 =
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0;
uint256 reinvest1 =
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1;
_deposit(
newLowerTick,
newUpperTick,
reinvest0,
reinvest1,
swapThresholdPrice,
swapAmountBPS,
zeroForOne
);
(newLiquidity, , , , ) = pool.positions(_getPositionID());
require(newLiquidity > 0, "new position 0");
} else {
lowerTick = newLowerTick;
upperTick = newUpperTick;
}
emit Rebalance(newLowerTick, newUpperTick, liquidity, newLiquidity);
}
// Gelatofied functions => Automatically called by Gelato
/// @notice Reinvest fees earned into underlying position, only gelato executors can call
/// Position bounds CANNOT be altered by gelato, only manager may via executiveRebalance.
/// Frequency of rebalance configured with gelatoRebalanceBPS, alterable by manager.
function rebalance(
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne,
uint256 feeAmount,
address paymentToken
) external gelatofy(feeAmount, paymentToken) {
if (swapAmountBPS > 0) {
_checkSlippage(swapThresholdPrice, zeroForOne);
}
(uint128 liquidity, , , , ) = pool.positions(_getPositionID());
_rebalance(
liquidity,
swapThresholdPrice,
swapAmountBPS,
zeroForOne,
feeAmount,
paymentToken
);
(uint128 newLiquidity, , , , ) = pool.positions(_getPositionID());
require(newLiquidity > liquidity, "liquidity must increase");
emit Rebalance(lowerTick, upperTick, liquidity, newLiquidity);
}
/// @notice withdraw manager fees accrued
function withdrawManagerBalance() external {
uint256 amount0 = managerBalance0;
uint256 amount1 = managerBalance1;
managerBalance0 = 0;
managerBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(managerTreasury, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(managerTreasury, amount1);
}
}
/// @notice withdraw arrakis fees accrued
function withdrawArrakisBalance() external {
uint256 amount0 = arrakisBalance0;
uint256 amount1 = arrakisBalance1;
arrakisBalance0 = 0;
arrakisBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(arrakisTreasury, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(arrakisTreasury, amount1);
}
}
// View functions
/// @notice compute maximum shares that can be minted from `amount0Max` and `amount1Max`
/// @param amount0Max The maximum amount of token0 to forward on mint
/// @param amount0Max The maximum amount of token1 to forward on mint
/// @return amount0 actual amount of token0 to forward when minting `mintAmount`
/// @return amount1 actual amount of token1 to forward when minting `mintAmount`
/// @return mintAmount maximum number of shares mintable
function getMintAmounts(uint256 amount0Max, uint256 amount1Max)
external
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
)
{
uint256 totalSupply = totalSupply();
if (totalSupply > 0) {
(amount0, amount1, mintAmount) = _computeMintAmounts(
totalSupply,
amount0Max,
amount1Max
);
} else {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 newLiquidity =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
amount0Max,
amount1Max
);
mintAmount = uint256(newLiquidity);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
newLiquidity
);
}
}
/// @notice compute total underlying holdings of the G-UNI token supply
/// includes current liquidity invested in uniswap position, current fees earned
/// and any uninvested leftover (but does not include manager or gelato fees accrued)
/// @return amount0Current current total underlying balance of token0
/// @return amount1Current current total underlying balance of token1
function getUnderlyingBalances()
public
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(uint160 sqrtRatioX96, int24 tick, , , , , ) = pool.slot0();
return _getUnderlyingBalances(sqrtRatioX96, tick);
}
function getUnderlyingBalancesAtPrice(uint160 sqrtRatioX96)
external
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(, int24 tick, , , , , ) = pool.slot0();
return _getUnderlyingBalances(sqrtRatioX96, tick);
}
// solhint-disable-next-line function-max-lines
function _getUnderlyingBalances(uint160 sqrtRatioX96, int24 tick)
internal
view
returns (uint256 amount0Current, uint256 amount1Current)
{
(
uint128 liquidity,
uint256 feeGrowthInside0Last,
uint256 feeGrowthInside1Last,
uint128 tokensOwed0,
uint128 tokensOwed1
) = pool.positions(_getPositionID());
// compute current holdings from liquidity
(amount0Current, amount1Current) = LiquidityAmounts
.getAmountsForLiquidity(
sqrtRatioX96,
lowerTick.getSqrtRatioAtTick(),
upperTick.getSqrtRatioAtTick(),
liquidity
);
// compute current fees earned
uint256 fee0 =
_computeFeesEarned(true, feeGrowthInside0Last, tick, liquidity) +
uint256(tokensOwed0);
uint256 fee1 =
_computeFeesEarned(false, feeGrowthInside1Last, tick, liquidity) +
uint256(tokensOwed1);
(fee0, fee1) = _subtractAdminFees(fee0, fee1);
// add any leftover in contract to current holdings
amount0Current +=
fee0 +
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0;
amount1Current +=
fee1 +
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1;
}
// Private functions
// solhint-disable-next-line function-max-lines
function _rebalance(
uint128 liquidity,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne,
uint256 feeAmount,
address paymentToken
) private {
uint256 leftover0 =
token0.balanceOf(address(this)) - managerBalance0 - arrakisBalance0;
uint256 leftover1 =
token1.balanceOf(address(this)) - managerBalance1 - arrakisBalance1;
(, , uint256 feesEarned0, uint256 feesEarned1) =
_withdraw(lowerTick, upperTick, liquidity);
_applyFees(feesEarned0, feesEarned1);
(feesEarned0, feesEarned1) = _subtractAdminFees(
feesEarned0,
feesEarned1
);
emit FeesEarned(feesEarned0, feesEarned1);
feesEarned0 += leftover0;
feesEarned1 += leftover1;
if (paymentToken == address(token0)) {
require(
(feesEarned0 * gelatoRebalanceBPS) / 10000 >= feeAmount,
"high fee"
);
leftover0 =
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0 -
feeAmount;
leftover1 =
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1;
} else if (paymentToken == address(token1)) {
require(
(feesEarned1 * gelatoRebalanceBPS) / 10000 >= feeAmount,
"high fee"
);
leftover0 =
token0.balanceOf(address(this)) -
managerBalance0 -
arrakisBalance0;
leftover1 =
token1.balanceOf(address(this)) -
managerBalance1 -
arrakisBalance1 -
feeAmount;
} else {
revert("wrong token");
}
_deposit(
lowerTick,
upperTick,
leftover0,
leftover1,
swapThresholdPrice,
swapAmountBPS,
zeroForOne
);
}
// solhint-disable-next-line function-max-lines
function _withdraw(
int24 lowerTick_,
int24 upperTick_,
uint128 liquidity
)
private
returns (
uint256 burn0,
uint256 burn1,
uint256 fee0,
uint256 fee1
)
{
uint256 preBalance0 = token0.balanceOf(address(this));
uint256 preBalance1 = token1.balanceOf(address(this));
(burn0, burn1) = pool.burn(lowerTick_, upperTick_, liquidity);
pool.collect(
address(this),
lowerTick_,
upperTick_,
type(uint128).max,
type(uint128).max
);
fee0 = token0.balanceOf(address(this)) - preBalance0 - burn0;
fee1 = token1.balanceOf(address(this)) - preBalance1 - burn1;
}
// solhint-disable-next-line function-max-lines
function _deposit(
int24 lowerTick_,
int24 upperTick_,
uint256 amount0,
uint256 amount1,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) private {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
// First, deposit as much as we can
uint128 baseLiquidity =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick_.getSqrtRatioAtTick(),
upperTick_.getSqrtRatioAtTick(),
amount0,
amount1
);
if (baseLiquidity > 0) {
(uint256 amountDeposited0, uint256 amountDeposited1) =
pool.mint(
address(this),
lowerTick_,
upperTick_,
baseLiquidity,
""
);
amount0 -= amountDeposited0;
amount1 -= amountDeposited1;
}
int256 swapAmount =
SafeCast.toInt256(
((zeroForOne ? amount0 : amount1) * swapAmountBPS) / 10000
);
if (swapAmount > 0) {
_swapAndDeposit(
lowerTick_,
upperTick_,
amount0,
amount1,
swapAmount,
swapThresholdPrice,
zeroForOne
);
}
}
function _swapAndDeposit(
int24 lowerTick_,
int24 upperTick_,
uint256 amount0,
uint256 amount1,
int256 swapAmount,
uint160 swapThresholdPrice,
bool zeroForOne
) private returns (uint256 finalAmount0, uint256 finalAmount1) {
(int256 amount0Delta, int256 amount1Delta) =
pool.swap(
address(this),
zeroForOne,
swapAmount,
swapThresholdPrice,
""
);
finalAmount0 = uint256(SafeCast.toInt256(amount0) - amount0Delta);
finalAmount1 = uint256(SafeCast.toInt256(amount1) - amount1Delta);
// Add liquidity a second time
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 liquidityAfterSwap =
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerTick_.getSqrtRatioAtTick(),
upperTick_.getSqrtRatioAtTick(),
finalAmount0,
finalAmount1
);
if (liquidityAfterSwap > 0) {
pool.mint(
address(this),
lowerTick_,
upperTick_,
liquidityAfterSwap,
""
);
}
}
// solhint-disable-next-line function-max-lines, code-complexity
function _computeMintAmounts(
uint256 totalSupply,
uint256 amount0Max,
uint256 amount1Max
)
private
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
)
{
(uint256 amount0Current, uint256 amount1Current) =
getUnderlyingBalances();
// compute proportional amount of tokens to mint
if (amount0Current == 0 && amount1Current > 0) {
mintAmount = FullMath.mulDiv(
amount1Max,
totalSupply,
amount1Current
);
} else if (amount1Current == 0 && amount0Current > 0) {
mintAmount = FullMath.mulDiv(
amount0Max,
totalSupply,
amount0Current
);
} else if (amount0Current == 0 && amount1Current == 0) {
revert("");
} else {
// only if both are non-zero
uint256 amount0Mint =
FullMath.mulDiv(amount0Max, totalSupply, amount0Current);
uint256 amount1Mint =
FullMath.mulDiv(amount1Max, totalSupply, amount1Current);
require(amount0Mint > 0 && amount1Mint > 0, "mint 0");
mintAmount = amount0Mint < amount1Mint ? amount0Mint : amount1Mint;
}
// compute amounts owed to contract
amount0 = FullMath.mulDivRoundingUp(
mintAmount,
amount0Current,
totalSupply
);
amount1 = FullMath.mulDivRoundingUp(
mintAmount,
amount1Current,
totalSupply
);
}
// solhint-disable-next-line function-max-lines
function _computeFeesEarned(
bool isZero,
uint256 feeGrowthInsideLast,
int24 tick,
uint128 liquidity
) private view returns (uint256 fee) {
uint256 feeGrowthOutsideLower;
uint256 feeGrowthOutsideUpper;
uint256 feeGrowthGlobal;
if (isZero) {
feeGrowthGlobal = pool.feeGrowthGlobal0X128();
(, , feeGrowthOutsideLower, , , , , ) = pool.ticks(lowerTick);
(, , feeGrowthOutsideUpper, , , , , ) = pool.ticks(upperTick);
} else {
feeGrowthGlobal = pool.feeGrowthGlobal1X128();
(, , , feeGrowthOutsideLower, , , , ) = pool.ticks(lowerTick);
(, , , feeGrowthOutsideUpper, , , , ) = pool.ticks(upperTick);
}
unchecked {
// calculate fee growth below
uint256 feeGrowthBelow;
if (tick >= lowerTick) {
feeGrowthBelow = feeGrowthOutsideLower;
} else {
feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower;
}
// calculate fee growth above
uint256 feeGrowthAbove;
if (tick < upperTick) {
feeGrowthAbove = feeGrowthOutsideUpper;
} else {
feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper;
}
uint256 feeGrowthInside =
feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove;
fee = FullMath.mulDiv(
liquidity,
feeGrowthInside - feeGrowthInsideLast,
0x100000000000000000000000000000000
);
}
}
function _applyFees(uint256 _fee0, uint256 _fee1) private {
arrakisBalance0 += (_fee0 * arrakisFeeBPS) / 10000;
arrakisBalance1 += (_fee1 * arrakisFeeBPS) / 10000;
managerBalance0 += (_fee0 * managerFeeBPS) / 10000;
managerBalance1 += (_fee1 * managerFeeBPS) / 10000;
}
function _subtractAdminFees(uint256 rawFee0, uint256 rawFee1)
private
view
returns (uint256 fee0, uint256 fee1)
{
uint256 deduct0 = (rawFee0 * (arrakisFeeBPS + managerFeeBPS)) / 10000;
uint256 deduct1 = (rawFee1 * (arrakisFeeBPS + managerFeeBPS)) / 10000;
fee0 = rawFee0 - deduct0;
fee1 = rawFee1 - deduct1;
}
function _checkSlippage(uint160 swapThresholdPrice, bool zeroForOne)
private
view
{
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = gelatoSlippageInterval;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
require(tickCumulatives.length == 2, "array len");
uint160 avgSqrtRatioX96;
unchecked {
int24 avgTick =
int24(
(tickCumulatives[1] - tickCumulatives[0]) /
int56(uint56(gelatoSlippageInterval))
);
avgSqrtRatioX96 = avgTick.getSqrtRatioAtTick();
}
uint160 maxSlippage = (avgSqrtRatioX96 * gelatoSlippageBPS) / 10000;
if (zeroForOne) {
require(
swapThresholdPrice >= avgSqrtRatioX96 - maxSlippage,
"high slippage"
);
} else {
require(
swapThresholdPrice <= avgSqrtRatioX96 + maxSlippage,
"high slippage"
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {Gelatofied} from "./Gelatofied.sol";
import {OwnableUninitialized} from "./OwnableUninitialized.sol";
import {
IUniswapV3Pool
} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
/// @dev Single Global upgradeable state var storage base: APPEND ONLY
/// @dev Add all inherited contracts with state vars here: APPEND ONLY
/// @dev ERC20Upgradable Includes Initialize
// solhint-disable-next-line max-states-count
abstract contract ArrakisVaultV1Storage is
ERC20Upgradeable, /* XXXX DONT MODIFY ORDERING XXXX */
ReentrancyGuardUpgradeable,
OwnableUninitialized,
Gelatofied
// APPEND ADDITIONAL BASE WITH STATE VARS BELOW:
// XXXX DONT MODIFY ORDERING XXXX
{
// solhint-disable-next-line const-name-snakecase
string public constant version = "1.0.0";
// solhint-disable-next-line const-name-snakecase
uint16 public constant arrakisFeeBPS = 250;
/// @dev "restricted mint enabled" toggle value must be a number
// above 10000 to safely avoid collisions for repurposed state var
uint16 public constant RESTRICTED_MINT_ENABLED = 11111;
address public immutable arrakisTreasury;
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
int24 public lowerTick;
int24 public upperTick;
uint16 public gelatoRebalanceBPS;
uint16 public restrictedMintToggle;
uint16 public gelatoSlippageBPS;
uint32 public gelatoSlippageInterval;
uint16 public managerFeeBPS;
address public managerTreasury;
uint256 public managerBalance0;
uint256 public managerBalance1;
uint256 public arrakisBalance0;
uint256 public arrakisBalance1;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
// APPPEND ADDITIONAL STATE VARS BELOW:
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
event UpdateManagerParams(
uint16 managerFeeBPS,
address managerTreasury,
uint16 gelatoRebalanceBPS,
uint16 gelatoSlippageBPS,
uint32 gelatoSlippageInterval
);
// solhint-disable-next-line max-line-length
constructor(address payable _gelato, address _arrakisTreasury)
Gelatofied(_gelato)
{
arrakisTreasury = _arrakisTreasury;
}
/// @notice initialize storage variables on a new G-UNI pool, only called once
/// @param _name name of Vault (immutable)
/// @param _symbol symbol of Vault (immutable)
/// @param _pool address of Uniswap V3 pool (immutable)
/// @param _managerFeeBPS proportion of fees earned that go to manager treasury
/// @param _lowerTick initial lowerTick (only changeable with executiveRebalance)
/// @param _lowerTick initial upperTick (only changeable with executiveRebalance)
/// @param _manager_ address of manager (ownership can be transferred)
function initialize(
string memory _name,
string memory _symbol,
address _pool,
uint16 _managerFeeBPS,
int24 _lowerTick,
int24 _upperTick,
address _manager_
) external initializer {
require(_managerFeeBPS <= 10000 - arrakisFeeBPS, "mBPS");
// these variables are immutable after initialization
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
// these variables can be udpated by the manager
_manager = _manager_;
managerFeeBPS = _managerFeeBPS;
managerTreasury = _manager_; // default: treasury is admin
gelatoSlippageInterval = 5 minutes; // default: last five minutes;
gelatoSlippageBPS = 500; // default: 5% slippage
gelatoRebalanceBPS = 200; // default: only rebalance if tx fee is lt 2% reinvested
lowerTick = _lowerTick;
upperTick = _upperTick;
// e.g. "Gelato Uniswap V3 USDC/DAI LP" and "G-UNI"
__ERC20_init(_name, _symbol);
__ReentrancyGuard_init();
}
/// @notice change configurable gelato parameters, only manager can call
/// @param newManagerFeeBPS Basis Points of fees earned credited to manager (negative to ignore)
/// @param newManagerTreasury address that collects manager fees (Zero address to ignore)
/// @param newRebalanceBPS threshold fees earned for gelato rebalances (negative to ignore)
/// @param newSlippageBPS frontrun protection parameter (negative to ignore)
/// @param newSlippageInterval frontrun protection parameter (negative to ignore)
// solhint-disable-next-line code-complexity
function updateManagerParams(
int16 newManagerFeeBPS,
address newManagerTreasury,
int16 newRebalanceBPS,
int16 newSlippageBPS,
int32 newSlippageInterval
) external onlyManager {
require(newRebalanceBPS <= 10000, "BPS");
require(newSlippageBPS <= 10000, "BPS");
require(newManagerFeeBPS <= 10000 - int16(arrakisFeeBPS), "mBPS");
if (newManagerFeeBPS >= 0) managerFeeBPS = uint16(newManagerFeeBPS);
if (newRebalanceBPS >= 0) gelatoRebalanceBPS = uint16(newRebalanceBPS);
if (newSlippageBPS >= 0) gelatoSlippageBPS = uint16(newSlippageBPS);
if (newSlippageInterval >= 0)
gelatoSlippageInterval = uint32(newSlippageInterval);
if (address(0) != newManagerTreasury)
managerTreasury = newManagerTreasury;
emit UpdateManagerParams(
managerFeeBPS,
managerTreasury,
gelatoRebalanceBPS,
gelatoSlippageBPS,
gelatoSlippageInterval
);
}
function toggleRestrictMint() external onlyManager {
if (restrictedMintToggle == RESTRICTED_MINT_ENABLED) {
restrictedMintToggle = 0;
} else {
restrictedMintToggle = RESTRICTED_MINT_ENABLED;
}
}
function renounceOwnership() public virtual override onlyManager {
managerTreasury = address(0);
managerFeeBPS = 0;
managerBalance0 = 0;
managerBalance1 = 0;
super.renounceOwnership();
}
function getPositionID() external view returns (bytes32 positionID) {
return _getPositionID();
}
function _getPositionID() internal view returns (bytes32 positionID) {
return keccak256(abi.encodePacked(address(this), lowerTick, upperTick));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage
abstract contract Gelatofied {
using Address for address payable;
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
address payable public immutable GELATO;
address private constant _ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(address payable _gelato) {
GELATO = _gelato;
}
modifier gelatofy(uint256 _amount, address _paymentToken) {
require(msg.sender == GELATO, "Gelatofied: Only gelato");
_;
if (_paymentToken == _ETH) GELATO.sendValue(_amount);
else IERC20(_paymentToken).safeTransfer(GELATO, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an manager) that can be granted exclusive access to
* specific functions.
*
* By default, the manager 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
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
/// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage
abstract contract OwnableUninitialized {
address internal _manager;
event OwnershipTransferred(
address indexed previousManager,
address indexed newManager
);
/// @dev Initializes the contract setting the deployer as the initial manager.
/// CONSTRUCTOR EMPTY - USE INITIALIZIABLE INSTEAD
// solhint-disable-next-line no-empty-blocks
constructor() {}
/**
* @dev Returns the address of the current manager.
*/
function manager() public view virtual returns (address) {
return _manager;
}
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(manager() == msg.sender, "Ownable: caller is not the manager");
_;
}
/**
* @dev Leaves the contract without manager. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current manager.
*
* NOTE: Renouncing ownership will leave the contract without an manager,
* thereby removing any functionality that is only available to the manager.
*/
function renounceOwnership() public virtual onlyManager {
emit OwnershipTransferred(_manager, address(0));
_manager = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current manager.
*/
function transferOwnership(address newOwner) public virtual onlyManager {
require(
newOwner != address(0),
"Ownable: new manager is the zero address"
);
emit OwnershipTransferred(_manager, newOwner);
_manager = newOwner;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// EDIT for 0.8 compatibility:
// see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import {FullMath} from "./FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate =
FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return
toUint128(
FullMath.mulDiv(
amount0,
intermediate,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
toUint128(
FullMath.mulDiv(
amount1,
FixedPoint96.Q96,
sqrtRatioBX96 - sqrtRatioAX96
)
);
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(
sqrtRatioAX96,
sqrtRatioBX96,
amount0
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 =
getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 =
getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(
sqrtRatioAX96,
sqrtRatioBX96,
amount1
);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount0 The amount0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The liquidity being valued
/// @return amount1 The amount1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
liquidity,
sqrtRatioBX96 - sqrtRatioAX96,
FixedPoint96.Q96
);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96)
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(
sqrtRatioX96,
sqrtRatioBX96,
liquidity
);
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioX96,
liquidity
);
} else {
amount1 = getAmount1ForLiquidity(
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick)
internal
pure
returns (uint160 sqrtPriceX96)
{
uint256 absTick =
tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
// EDIT: 0.8 compatibility
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio =
absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0)
ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0)
ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0)
ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0)
ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0)
ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0)
ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0)
ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0)
ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0)
ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0)
ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0)
ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0)
ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0)
ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0)
ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0)
ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0)
ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0)
ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0)
ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0)
ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160(
(ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
);
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96)
internal
pure
returns (int24 tick)
{
// second inequality must be < because the price can never reach the price at the max tick
require(
sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
"R"
);
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow =
int24(
(log_sqrt10001 - 3402992956809132418596140100660247210) >> 128
);
int24 tickHi =
int24(
(log_sqrt10001 + 291339464771989622907027621153398088495) >> 128
);
tick = tickLow == tickHi
? tickLow
: getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
? tickHi
: tickLow;
}
} | withdraw manager fees accrued | function withdrawManagerBalance() external {
uint256 amount0 = managerBalance0;
uint256 amount1 = managerBalance1;
managerBalance0 = 0;
managerBalance1 = 0;
if (amount0 > 0) {
token0.safeTransfer(managerTreasury, amount0);
}
if (amount1 > 0) {
token1.safeTransfer(managerTreasury, amount1);
}
}
| 14,726,168 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant 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 constant 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 BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
bool transferAllowed = false;
function setTransferAllowed(bool _transferAllowed) public onlyOwner {
transferAllowed = _transferAllowed;
}
/**
* @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]);
require(transferAllowed);
// 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 constant returns (uint256 balance) {
return balances[_owner];
}
}
//StandardToken.sol
contract StandardToken is ERC20, BasicToken {
using SafeMath for uint256;
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]);
require(transferAllowed);
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) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MatToken is Ownable, StandardToken {
string public constant name = "MiniApps Token";
string public constant symbol = "MAT";
uint public constant decimals = 18;
// token units
uint256 public constant MAT_UNIT = 10**uint256(decimals);
uint256 constant MILLION_MAT = 10**6 * MAT_UNIT;
uint256 constant THOUSAND_MAT = 10**3 * MAT_UNIT;
// Token distribution: crowdsale - 50%, partners - 35%, team - 15%, total 20M
uint256 public constant MAT_CROWDSALE_SUPPLY_LIMIT = 10 * MILLION_MAT;
uint256 public constant MAT_TEAM_SUPPLY_LIMIT = 7 * MILLION_MAT;
uint256 public constant MAT_PARTNERS_SUPPLY_LIMIT = 3 * MILLION_MAT;
uint256 public constant MAT_TOTAL_SUPPLY_LIMIT = MAT_CROWDSALE_SUPPLY_LIMIT + MAT_TEAM_SUPPLY_LIMIT + MAT_PARTNERS_SUPPLY_LIMIT;
}
contract MatBonus is MatToken {
uint256 public constant TOTAL_SUPPLY_UPPER_BOUND = 14000 * THOUSAND_MAT;
uint256 public constant TOTAL_SUPPLY_BOTTOM_BOUND = 11600 * THOUSAND_MAT;
function calcBonus(uint256 tokens) internal returns (uint256){
if (totalSupply <= TOTAL_SUPPLY_BOTTOM_BOUND)
return tokens.mul(8).div(100);
else if (totalSupply > TOTAL_SUPPLY_BOTTOM_BOUND && totalSupply <= TOTAL_SUPPLY_UPPER_BOUND)
return tokens.mul(5).div(100);
else
return 0;
}
}
contract MatBase is Ownable, MatToken, MatBonus {
using SafeMath for uint256;
uint256 public constant _START_DATE = 1508284800; // Wednesday, 18-Oct-17 00:00:00 UTC in RFC 2822
uint256 public constant _END_DATE = 1513641600; // Tuesday, 19-Dec-17 00:00:00 UTC in RFC 2822
uint256 public constant CROWDSALE_PRICE = 100; // 100 MAT per ETH
address public constant ICO_ADDRESS = 0x6075a5A0620861cfeF593a51A01aF0fF179168C7;
address public constant PARTNERS_WALLET = 0x39467d5B39F1d24BC8479212CEd151ad469B0D7E;
address public constant TEAM_WALLET = 0xe1d32147b08b2a7808026D4A94707E321ccc7150;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
function setStartTime(uint256 _startTime) onlyOwner
{
startTime = _startTime;
}
function setEndTime(uint256 _endTime) onlyOwner
{
endTime = _endTime;
}
// address where funds are collected
address public wallet;
address public p_wallet;
address public t_wallet;
// total amount of raised money in wei
uint256 public totalCollected;
// how many token units a buyer gets per wei
uint256 public rate;
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
event Mint(address indexed purchaser, uint256 amount);
event Bonus(address indexed purchaser,uint256 amount);
function mint(address _to, uint256 _tokens) internal returns (bool) {
totalSupply = totalSupply.add(_tokens);
require(totalSupply <= whiteListLimit);
require(totalSupply <= MAT_TOTAL_SUPPLY_LIMIT);
balances[_to] = balances[_to].add(_tokens);
Mint(_to, _tokens);
Transfer(0x0, _to, _tokens);
return true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
/**
* 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 amountTokens amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amountTokens,
string referral);
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
buyTokensReferral(beneficiary, "");
}
// low level token purchase function
function buyTokensReferral(address beneficiary, string referral) public payable {
require(msg.value > 0);
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
uint256 bonus = calcBonus(tokens);
// update state
totalCollected = totalCollected.add(weiAmount);
if (!buyTokenWL(tokens)) mint(beneficiary, bonus);
mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, referral);
forwardFunds();
}
//whitelist
bool isWhitelistOn;
uint256 public whiteListLimit;
enum WLS {notlisted,listed,fulfilled}
struct FundReservation {
WLS status;
uint256 reserved;
}
mapping ( address => FundReservation ) whitelist;
function stopWhitelistReservetion() onlyOwner public {
whiteListLimit = MAT_TOTAL_SUPPLY_LIMIT;
}
function setWhiteListStatus(bool _isWhitelistOn) onlyOwner public {
isWhitelistOn = _isWhitelistOn;
}
function buyTokenWL(uint256 tokens) internal returns (bool)
{
require(isWhitelistOn);
require(now >= startTime);
if (whitelist[msg.sender].status == WLS.listed) {
uint256 reservation = whitelist[msg.sender].reserved;
uint256 low = reservation.mul(9).div(10);
uint256 upper = reservation.mul(11).div(10);
if( low <= msg.value && msg.value <= upper) {
whitelist[msg.sender].status == WLS.fulfilled;
uint256 bonus = tokens / 10;
mint(msg.sender, bonus);
Bonus(msg.sender,bonus);
return true;
}
}
return false;
}
event White(address indexed to, uint256 reservation);
function regWL(address wlmember, uint256 reservation) onlyOwner public returns (bool status)
{
require(now < endTime);
require(whitelist[wlmember].status == WLS.notlisted);
whitelist[wlmember].status = WLS.listed;
whitelist[wlmember].reserved = reservation;
whiteListLimit = whiteListLimit.sub(reservation.mul(CROWDSALE_PRICE).mul(11).div(10));
White(wlmember,reservation);
return true;
}
address public constant PRESALE_CONTRACT = 0x503FE694CE047eCB51952b79eCAB2A907Afe8ACd;
/**
* @dev presale token conversion
*
* @param _to holder of presale tokens
* @param _pretokens The amount of presale tokens to be spent.
* @param _tokens The amount of presale tokens to be minted on crowdsale, the rest transfer from partners pool
*/
function convert(address _to, uint256 _pretokens, uint256 _tokens) onlyOwner public returns (bool){
require(now <= endTime);
require(_to != address(0));
require(_pretokens >= _tokens);
mint(_to, _tokens); //implicit transfer event
uint256 theRest = _pretokens.sub(_tokens);
require(balances[PARTNERS_WALLET] >= theRest);
if (theRest > 0) {
balances[PARTNERS_WALLET] = balances[PARTNERS_WALLET].sub(theRest);
balances[_to] = balances[_to].add(theRest);
Transfer(PARTNERS_WALLET, _to, theRest); //explicit transfer event
}
uint256 amount = _pretokens.div(rate);
totalCollected = totalCollected.add(amount);
return true;
}
function MatBase() {
startTime = _START_DATE;
endTime = _END_DATE;
wallet = ICO_ADDRESS;
rate = CROWDSALE_PRICE;
p_wallet = PARTNERS_WALLET;
t_wallet = TEAM_WALLET;
balances[p_wallet] = MAT_PARTNERS_SUPPLY_LIMIT;
balances[t_wallet] = MAT_TEAM_SUPPLY_LIMIT;
totalSupply = MAT_PARTNERS_SUPPLY_LIMIT + MAT_TEAM_SUPPLY_LIMIT;
whiteListLimit = MAT_TOTAL_SUPPLY_LIMIT;
}
} | presale token conversion _to holder of presale tokens _pretokens The amount of presale tokens to be spent. _tokens The amount of presale tokens to be minted on crowdsale, the rest transfer from partners pool/ | function convert(address _to, uint256 _pretokens, uint256 _tokens) onlyOwner public returns (bool){
require(now <= endTime);
require(_to != address(0));
require(_pretokens >= _tokens);
uint256 theRest = _pretokens.sub(_tokens);
require(balances[PARTNERS_WALLET] >= theRest);
if (theRest > 0) {
balances[PARTNERS_WALLET] = balances[PARTNERS_WALLET].sub(theRest);
balances[_to] = balances[_to].add(theRest);
}
uint256 amount = _pretokens.div(rate);
totalCollected = totalCollected.add(amount);
return true;
}
| 12,902,409 |
./full_match/80001/0x281D1c6Ee5CCd86102A1369D9ED0921A84F44278/sources/Contracts/USTFeeder.sol | burn part of the UST keep the remaining luna send NVB back end the transactions get UST burn luna transfer the remaining luna to LP walled send NVB back | function getNVB(uint256 _amount, uint256 _burningmultiplier) public {
require(_amount > 1000000, "Amount should be at least 1 UST");
if (_burningmultiplier > 90) _burningmultiplier = 90;
uint256 burned = (_amount * _burningmultiplier) / 100;
_burnedUST += burned / (10 ** 6);
uint256 remaining = _amount - burned;
uint256 NVBAmount = getNVBamount(remaining);
require(NVBAmount < _NVBStake, "The rewards are not enought");
_NVBStake -= NVBAmount * 10 ** 6;
IERC20(_USTAddr).transferFrom(msg.sender, address(this), _amount);
IERC20(_USTAddr).transfer(_burnWalled, burned);
IERC20(_USTAddr).transfer(_receiverAddr, remaining);
IERC20(_NVBAddr).transfer(msg.sender, NVBAmount);
}
| 5,656,678 |
./full_match/1/0x215662DB3cF2d7dCC8E8547a40C264381100A947/sources/contracts/UbeFactory.sol | pay the tip with tokens (in wei) Buy me a tea | function buyTea(uint256 in_wei, address from_address) public {
require(enableTea, "WPIC deployments are not enabled now");
token.transferFrom(from_address, masterAddress, getPriceInToken(in_wei));
}
| 2,912,486 |
pragma solidity ^0.4.19;
contract Engine {
uint256 public VERSION;
string public VERSION_NAME;
enum Status { initial, lent, paid, destroyed }
struct Approbation {
bool approved;
bytes data;
bytes32 checksum;
}
function getTotalLoans() public view returns (uint256);
function getOracle(uint index) public view returns (Oracle);
function getBorrower(uint index) public view returns (address);
function getCosigner(uint index) public view returns (address);
function ownerOf(uint256) public view returns (address owner);
function getCreator(uint index) public view returns (address);
function getAmount(uint index) public view returns (uint256);
function getPaid(uint index) public view returns (uint256);
function getDueTime(uint index) public view returns (uint256);
function getApprobation(uint index, address _address) public view returns (bool);
function getStatus(uint index) public view returns (Status);
function isApproved(uint index) public view returns (bool);
function getPendingAmount(uint index) public returns (uint256);
function getCurrency(uint index) public view returns (bytes32);
function cosign(uint index, uint256 cost) external returns (bool);
function approveLoan(uint index) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
function takeOwnership(uint256 index) public returns (bool);
function withdrawal(uint index, address to, uint256 amount) public returns (bool);
}
/**
@dev Defines the interface of a standard RCN cosigner.
The cosigner is an agent that gives an insurance to the lender in the event of a defaulted loan, the confitions
of the insurance and the cost of the given are defined by the cosigner.
The lender will decide what cosigner to use, if any; the address of the cosigner and the valid data provided by the
agent should be passed as params when the lender calls the "lend" method on the engine.
When the default conditions defined by the cosigner aligns with the status of the loan, the lender of the engine
should be able to call the "claim" method to receive the benefit; the cosigner can define aditional requirements to
call this method, like the transfer of the ownership of the loan.
*/
contract Cosigner {
uint256 public constant VERSION = 2;
/**
@return the url of the endpoint that exposes the insurance offers.
*/
function url() public view returns (string);
/**
@dev Retrieves the cost of a given insurance, this amount should be exact.
@return the cost of the cosign, in RCN wei
*/
function cost(address engine, uint256 index, bytes data, bytes oracleData) public view returns (uint256);
/**
@dev The engine calls this method for confirmation of the conditions, if the cosigner accepts the liability of
the insurance it must call the method "cosign" of the engine. If the cosigner does not call that method, or
does not return true to this method, the operation fails.
@return true if the cosigner accepts the liability
*/
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool);
/**
@dev Claims the benefit of the insurance if the loan is defaulted, this method should be only calleable by the
current lender of the loan.
@return true if the claim was done correctly.
*/
function claim(address engine, uint256 index, bytes oracleData) public returns (bool);
}
contract ERC721 {
// ERC20 compatible functions
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint _balance);
// Functions that define ownership
function ownerOf(uint256) public view returns (address owner);
function approve(address, uint256) public returns (bool);
function takeOwnership(uint256) public returns (bool);
function transfer(address, uint256) public returns (bool);
function setApprovalForAll(address _operator, bool _approved) public returns (bool);
function getApproved(uint256 _tokenId) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
// Token metadata
function tokenMetadata(uint256 _tokenId) public view returns (string info);
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
}
contract Token {
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function approve(address _spender, uint256 _value) public returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
}
contract Ownable {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Ownable() public {
owner = msg.sender;
}
/**
@dev Transfers the ownership of the contract.
@param _to Address of the new owner
*/
function transferTo(address _to) public onlyOwner returns (bool) {
require(_to != address(0));
owner = _to;
return true;
}
}
/**
@dev Defines the interface of a standard RCN oracle.
The oracle is an agent in the RCN network that supplies a convertion rate between RCN and any other currency,
it's primarily used by the exchange but could be used by any other agent.
*/
contract Oracle is Ownable {
uint256 public constant VERSION = 3;
event NewSymbol(bytes32 _currency, string _ticker);
struct Symbol {
string ticker;
bool supported;
}
mapping(bytes32 => Symbol) public currencies;
/**
@dev Returns the url where the oracle exposes a valid "oracleData" if needed
*/
function url() public view returns (string);
/**
@dev Returns a valid convertion rate from the currency given to RCN
@param symbol Symbol of the currency
@param data Generic data field, could be used for off-chain signing
*/
function getRate(bytes32 symbol, bytes data) public returns (uint256 rate, uint256 decimals);
/**
@dev Adds a currency to the oracle, once added it cannot be removed
@param ticker Symbol of the currency
@return the hash of the currency, calculated keccak256(ticker)
*/
function addCurrency(string ticker) public onlyOwner returns (bytes32) {
NewSymbol(currency, ticker);
bytes32 currency = keccak256(ticker);
currencies[currency] = Symbol(ticker, true);
return currency;
}
/**
@return true If the currency is supported
*/
function supported(bytes32 symbol) public view returns (bool) {
return currencies[symbol].supported;
}
}
contract RpSafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
require(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y));
return z;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns(uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
}
contract TokenLockable is RpSafeMath, Ownable {
mapping(address => uint256) public lockedTokens;
/**
@dev Locked tokens cannot be withdrawn using the withdrawTokens function.
*/
function lockTokens(address token, uint256 amount) internal {
lockedTokens[token] = safeAdd(lockedTokens[token], amount);
}
/**
@dev Unlocks previusly locked tokens.
*/
function unlockTokens(address token, uint256 amount) internal {
lockedTokens[token] = safeSubtract(lockedTokens[token], amount);
}
/**
@dev Withdraws tokens from the contract.
@param token Token to withdraw
@param to Destination of the tokens
@param amount Amount to withdraw
*/
function withdrawTokens(Token token, address to, uint256 amount) public onlyOwner returns (bool) {
require(safeSubtract(token.balanceOf(this), lockedTokens[token]) >= amount);
require(to != address(0));
return token.transfer(to, amount);
}
}
contract NanoLoanEngine is ERC721, Engine, Ownable, TokenLockable {
uint256 constant internal PRECISION = (10**18);
uint256 constant internal RCN_DECIMALS = 18;
uint256 public constant VERSION = 232;
string public constant VERSION_NAME = "Basalt";
uint256 private activeLoans = 0;
mapping(address => uint256) private lendersBalance;
function name() public view returns (string _name) {
_name = "RCN - Nano loan engine - Basalt 232";
}
function symbol() public view returns (string _symbol) {
_symbol = "RCN-NLE-232";
}
/**
@notice Returns the number of active loans in total, active loans are the loans with "lent" status.
@dev Required for ERC-721 compliance
@return _totalSupply Total amount of loans
*/
function totalSupply() public view returns (uint _totalSupply) {
_totalSupply = activeLoans;
}
/**
@notice Returns the number of active loans that a lender possess; active loans are the loans with "lent" status.
@dev Required for ERC-721 compliance
@param _owner The owner address to search
@return _balance Amount of loans
*/
function balanceOf(address _owner) public view returns (uint _balance) {
_balance = lendersBalance[_owner];
}
/**
@notice Returns all the loans that a lender possess
@dev This method MUST NEVER be called by smart contract code;
it walks the entire loans array, and will probably create a transaction bigger than the gas limit.
@param _owner The owner address
@return ownerTokens List of all the loans of the _owner
*/
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalLoans = loans.length - 1;
uint256 resultIndex = 0;
uint256 loanId;
for (loanId = 0; loanId <= totalLoans; loanId++) {
if (loans[loanId].lender == _owner && loans[loanId].status == Status.lent) {
result[resultIndex] = loanId;
resultIndex++;
}
}
return result;
}
}
/**
@notice Returns true if the _operator can transfer the loans of the _owner
@dev Required for ERC-721 compliance
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operators[_owner][_operator];
}
/**
@notice Returns the loan metadata, this field can be set by the creator of the loan with his own criteria.
@param index Index of the loan
@return The string with the metadata
*/
function tokenMetadata(uint256 index) public view returns (string) {
return loans[index].metadata;
}
/**
@notice Returns the loan metadata, hashed with keccak256.
@dev This emthod is useful to evaluate metadata from a smart contract.
@param index Index of the loan
@return The metadata hashed with keccak256
*/
function tokenMetadataHash(uint256 index) public view returns (bytes32) {
return keccak256(loans[index].metadata);
}
Token public rcn;
bool public deprecated;
event CreatedLoan(uint _index, address _borrower, address _creator);
event ApprovedBy(uint _index, address _address);
event Lent(uint _index, address _lender, address _cosigner);
event DestroyedBy(uint _index, address _address);
event PartialPayment(uint _index, address _sender, address _from, uint256 _amount);
event TotalPayment(uint _index);
function NanoLoanEngine(Token _rcn) public {
owner = msg.sender;
rcn = _rcn;
// The loan 0 is a Invalid loan
loans.length++;
}
struct Loan {
Status status;
Oracle oracle;
address borrower;
address lender;
address creator;
address cosigner;
uint256 amount;
uint256 interest;
uint256 punitoryInterest;
uint256 interestTimestamp;
uint256 paid;
uint256 interestRate;
uint256 interestRatePunitory;
uint256 dueTime;
uint256 duesIn;
bytes32 currency;
uint256 cancelableAt;
uint256 lenderBalance;
address approvedTransfer;
uint256 expirationRequest;
string metadata;
mapping(address => bool) approbations;
}
mapping(address => mapping(address => bool)) private operators;
mapping(bytes32 => uint256) public identifierToIndex;
Loan[] private loans;
/**
@notice Creates a loan request, the loan can be generated with any borrower and conditions; if the borrower agrees
it must call the "approve" function. If the creator of the loan is the borrower the approve is done automatically.
@dev The creator of the loan is the caller of this function; this is useful to track which wallet created the loan.
Two identical loans cannot exist, a clone of another loan will fail.
@param _oracleContract Address of the Oracle contract, if the loan does not use any oracle, this field should be 0x0.
@param _borrower Address of the borrower
@param _currency The currency to use with the oracle, the currency code is generated with the following formula,
keccak256(ticker), is always stored as the minimum divisible amount. (Ej: ETH Wei, USD Cents)
@param _amount The requested amount; currency and unit are defined by the Oracle, if there is no Oracle present
the currency is RCN, and the unit is wei.
@param _interestRate The non-punitory interest rate by second, defined as a denominator of 10 000 000.
@param _interestRatePunitory The punitory interest rate by second, defined as a denominator of 10 000 000.
Ej: interestRate 11108571428571 = 28% Anual interest
@param _duesIn The time in seconds that the borrower has in order to pay the debt after the lender lends the money.
@param _cancelableAt Delta in seconds specifying how much interest should be added in advance, if the borrower pays
entirely or partially the loan before this term, no extra interest will be deducted.
@param _expirationRequest Timestamp of when the loan request expires, if the loan is not filled before this date,
the request is no longer valid.
@param _metadata String with loan metadata.
*/
function createLoan(Oracle _oracleContract, address _borrower, bytes32 _currency, uint256 _amount, uint256 _interestRate,
uint256 _interestRatePunitory, uint256 _duesIn, uint256 _cancelableAt, uint256 _expirationRequest, string _metadata) public returns (uint256) {
require(!deprecated);
require(_cancelableAt <= _duesIn);
require(_oracleContract != address(0) || _currency == 0x0);
require(_borrower != address(0));
require(_amount != 0);
require(_interestRatePunitory != 0);
require(_interestRate != 0);
require(_expirationRequest > block.timestamp);
var loan = Loan(Status.initial, _oracleContract, _borrower, 0x0, msg.sender, 0x0, _amount, 0, 0, 0, 0, _interestRate,
_interestRatePunitory, 0, _duesIn, _currency, _cancelableAt, 0, 0x0, _expirationRequest, _metadata);
uint index = loans.push(loan) - 1;
CreatedLoan(index, _borrower, msg.sender);
bytes32 identifier = getIdentifier(index);
require(identifierToIndex[identifier] == 0);
identifierToIndex[identifier] = index;
if (msg.sender == _borrower) {
approveLoan(index);
}
return index;
}
function ownerOf(uint256 index) public view returns (address owner) { owner = loans[index].lender; }
function getTotalLoans() public view returns (uint256) { return loans.length; }
function getOracle(uint index) public view returns (Oracle) { return loans[index].oracle; }
function getBorrower(uint index) public view returns (address) { return loans[index].borrower; }
function getCosigner(uint index) public view returns (address) { return loans[index].cosigner; }
function getCreator(uint index) public view returns (address) { return loans[index].creator; }
function getAmount(uint index) public view returns (uint256) { return loans[index].amount; }
function getPunitoryInterest(uint index) public view returns (uint256) { return loans[index].punitoryInterest; }
function getInterestTimestamp(uint index) public view returns (uint256) { return loans[index].interestTimestamp; }
function getPaid(uint index) public view returns (uint256) { return loans[index].paid; }
function getInterestRate(uint index) public view returns (uint256) { return loans[index].interestRate; }
function getInterestRatePunitory(uint index) public view returns (uint256) { return loans[index].interestRatePunitory; }
function getDueTime(uint index) public view returns (uint256) { return loans[index].dueTime; }
function getDuesIn(uint index) public view returns (uint256) { return loans[index].duesIn; }
function getCancelableAt(uint index) public view returns (uint256) { return loans[index].cancelableAt; }
function getApprobation(uint index, address _address) public view returns (bool) { return loans[index].approbations[_address]; }
function getStatus(uint index) public view returns (Status) { return loans[index].status; }
function getLenderBalance(uint index) public view returns (uint256) { return loans[index].lenderBalance; }
function getApproved(uint index) public view returns (address) {return loans[index].approvedTransfer; }
function getCurrency(uint index) public view returns (bytes32) { return loans[index].currency; }
function getExpirationRequest(uint index) public view returns (uint256) { return loans[index].expirationRequest; }
function getInterest(uint index) public view returns (uint256) { return loans[index].interest; }
function getIdentifier(uint index) public view returns (bytes32) {
Loan memory loan = loans[index];
return buildIdentifier(loan.oracle, loan.borrower, loan.creator, loan.currency, loan.amount, loan.interestRate,
loan.interestRatePunitory, loan.duesIn, loan.cancelableAt, loan.expirationRequest, loan.metadata);
}
/**
@notice Used to reference a loan that is not yet created, and by that does not have an index
@dev Two identical loans cannot exist, only one loan per signature is allowed
@return The signature hash of the loan configuration
*/
function buildIdentifier(Oracle oracle, address borrower, address creator, bytes32 currency, uint256 amount, uint256 interestRate,
uint256 interestRatePunitory, uint256 duesIn, uint256 cancelableAt, uint256 expirationRequest, string metadata) view returns (bytes32) {
return keccak256(this, oracle, borrower, creator, currency, amount, interestRate, interestRatePunitory, duesIn,
cancelableAt, expirationRequest, metadata);
}
/**
@notice Used to know if a loan is ready to lend
@param index Index of the loan
@return true if the loan has been approved by the borrower and cosigner.
*/
function isApproved(uint index) public view returns (bool) {
Loan storage loan = loans[index];
return loan.approbations[loan.borrower];
}
/**
@notice Called by the members of the loan to show that they agree with the terms of the loan; the borrower
must call this method before any lender could call the method "lend".
@dev Any address can call this method to be added to the "approbations" mapping.
@param index Index of the loan
@return true if the approve was done successfully
*/
function approveLoan(uint index) public returns(bool) {
Loan storage loan = loans[index];
require(loan.status == Status.initial);
loan.approbations[msg.sender] = true;
ApprovedBy(index, msg.sender);
return true;
}
/**
@notice Approves a loan using the Identifier and not the index
@param identifier Identifier of the loan
@return true if the approve was done successfully
*/
function approveLoanIdentifier(bytes32 identifier) public returns (bool) {
uint256 index = identifierToIndex[identifier];
require(index != 0);
return approveLoan(index);
}
/**
@notice Register an approvation made by a borrower in the past
@dev The loan should exist and have an index
@param identifier Identifier of the loan
@return true if the approve was done successfully
*/
function registerApprove(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) public returns (bool) {
uint256 index = identifierToIndex[identifier];
require(index != 0);
Loan storage loan = loans[index];
require(loan.borrower == ecrecover(keccak256("\x19Ethereum Signed Message:\n32", identifier), v, r, s));
loan.approbations[loan.borrower] = true;
ApprovedBy(index, loan.borrower);
return true;
}
/**
@notice Performs the lend of the RCN equivalent to the requested amount, and transforms the msg.sender in the new lender.
@dev The loan must be previously approved by the borrower; before calling this function, the lender candidate must
call the "approve" function on the RCN Token, specifying an amount sufficient enough to pay the equivalent of
the requested amount, and the cosigner fee.
@param index Index of the loan
@param oracleData Data required by the oracle to return the rate, the content of this field must be provided
by the url exposed in the url() method of the oracle.
@param cosigner Address of the cosigner, 0x0 for lending without cosigner.
@param cosignerData Data required by the cosigner to process the request.
@return true if the lend was done successfully
*/
function lend(uint index, bytes oracleData, Cosigner cosigner, bytes cosignerData) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.initial);
require(isApproved(index));
require(block.timestamp <= loan.expirationRequest);
loan.lender = msg.sender;
loan.dueTime = safeAdd(block.timestamp, loan.duesIn);
loan.interestTimestamp = block.timestamp;
loan.status = Status.lent;
// ERC721, create new loan and transfer it to the lender
Transfer(0x0, loan.lender, index);
activeLoans += 1;
lendersBalance[loan.lender] += 1;
if (loan.cancelableAt > 0)
internalAddInterest(loan, safeAdd(block.timestamp, loan.cancelableAt));
// Transfer the money to the borrower before handling the cosigner
// so the cosigner could require a specific usage for that money.
uint256 transferValue = convertRate(loan.oracle, loan.currency, oracleData, loan.amount);
require(rcn.transferFrom(msg.sender, loan.borrower, transferValue));
if (cosigner != address(0)) {
// The cosigner it's temporary set to the next address (cosigner + 2), it's expected that the cosigner will
// call the method "cosign" to accept the conditions; that method also sets the cosigner to the right
// address. If that does not happen, the transaction fails.
loan.cosigner = address(uint256(cosigner) + 2);
require(cosigner.requestCosign(this, index, cosignerData, oracleData));
require(loan.cosigner == address(cosigner));
}
Lent(index, loan.lender, cosigner);
return true;
}
/**
@notice The cosigner must call this method to accept the conditions of a loan, this method pays the cosigner his fee.
@dev If the cosigner does not call this method the whole "lend" call fails.
@param index Index of the loan
@param cost Fee set by the cosigner
@return true If the cosign was successfull
*/
function cosign(uint index, uint256 cost) external returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent && (loan.dueTime - loan.duesIn) == block.timestamp);
require(loan.cosigner != address(0));
require(loan.cosigner == address(uint256(msg.sender) + 2));
loan.cosigner = msg.sender;
require(rcn.transferFrom(loan.lender, msg.sender, cost));
return true;
}
/**
@notice Destroys a loan, the borrower could call this method if they performed an accidental or regretted
"approve" of the loan, this method only works for them if the loan is in "pending" status.
The lender can call this method at any moment, in case of a loan with status "lent" the lender is pardoning
the debt.
@param index Index of the loan
@return true if the destroy was done successfully
*/
function destroy(uint index) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status != Status.destroyed);
require(msg.sender == loan.lender || (msg.sender == loan.borrower && loan.status == Status.initial));
DestroyedBy(index, msg.sender);
// ERC721, remove loan from circulation
if (loan.status != Status.initial) {
lendersBalance[loan.lender] -= 1;
activeLoans -= 1;
Transfer(loan.lender, 0x0, index);
}
loan.status = Status.destroyed;
return true;
}
/**
@notice Destroys a loan using the signature and not the Index
@param identifier Identifier of the loan
@return true if the destroy was done successfully
*/
function destroyIdentifier(bytes32 identifier) public returns (bool) {
uint256 index = identifierToIndex[identifier];
require(index != 0);
return destroy(index);
}
/**
@notice Transfers a loan to a different lender, the caller must be the current lender or previously being
approved with the method "approveTransfer"; only loans with the Status.lent status can be transfered.
@dev Required for ERC-721 compliance
@param index Index of the loan
@param to New lender
@return true if the transfer was done successfully
*/
function transfer(address to, uint256 index) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender || msg.sender == loan.approvedTransfer || operators[loan.lender][msg.sender]);
require(to != address(0));
loan.lender = to;
loan.approvedTransfer = address(0);
// ERC721, transfer loan to another address
lendersBalance[msg.sender] -= 1;
lendersBalance[to] += 1;
Transfer(loan.lender, to, index);
return true;
}
/**
@notice Transfers the loan to the msg.sender, the msg.sender must be approved using the "approve" method.
@dev Required for ERC-721 compliance
@param _index Index of the loan
@return true if the transfer was successfull
*/
function takeOwnership(uint256 _index) public returns (bool) {
return transfer(msg.sender, _index);
}
/**
@notice Transfers the loan to an address, only if the current owner is the "from" address
@dev Required for ERC-721 compliance
@param from Current owner of the loan
@param to New owner of the loan
@param index Index of the loan
@return true if the transfer was successfull
*/
function transferFrom(address from, address to, uint256 index) public returns (bool) {
require(loans[index].lender == from);
return transfer(to, index);
}
/**
@notice Approves the transfer of a given loan in the name of the lender, the behavior of this function is similar to
"approve" in the ERC20 standard, but only one approved address is allowed at a time.
The same method can be called passing 0x0 as parameter "to" to erase a previously approved address.
@dev Required for ERC-721 compliance
@param to Address allowed to transfer the loan or 0x0 to delete
@param index Index of the loan
@return true if the approve was done successfully
*/
function approve(address to, uint256 index) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender);
loan.approvedTransfer = to;
Approval(msg.sender, to, index);
return true;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage
@param _approved True if the operator is approved, false to revoke approval
@param _operator Address to add to the set of authorized operators.
*/
function setApprovalForAll(address _operator, bool _approved) public returns (bool) {
operators[msg.sender][_operator] = _approved;
ApprovalForAll(msg.sender, _operator, _approved);
return true;
}
/**
@notice Returns the pending amount to complete de payment of the loan, keep in mind that this number increases
every second.
@dev This method also computes the interest and updates the loan
@param index Index of the loan
@return Aprox pending payment amount
*/
function getPendingAmount(uint index) public returns (uint256) {
addInterest(index);
return getRawPendingAmount(index);
}
/**
@notice Returns the pending amount up to the last time of the interest update. This is not the real pending amount
@dev This method is exact only if "addInterest(loan)" was before and in the same block.
@param index Index of the loan
@return The past pending amount
*/
function getRawPendingAmount(uint index) public view returns (uint256) {
Loan memory loan = loans[index];
return safeSubtract(safeAdd(safeAdd(loan.amount, loan.interest), loan.punitoryInterest), loan.paid);
}
/**
@notice Calculates the interest of a given amount, interest rate and delta time.
@param timeDelta Elapsed time
@param interestRate Interest rate expressed as the denominator of 10 000 000.
@param amount Amount to apply interest
@return realDelta The real timeDelta applied
@return interest The interest gained in the realDelta time
*/
function calculateInterest(uint256 timeDelta, uint256 interestRate, uint256 amount) internal pure returns (uint256 realDelta, uint256 interest) {
if (amount == 0) {
interest = 0;
realDelta = timeDelta;
} else {
interest = safeMult(safeMult(100000, amount), timeDelta) / interestRate;
realDelta = safeMult(interest, interestRate) / (amount * 100000);
}
}
/**
@notice Computes loan interest
Computes the punitory and non-punitory interest of a given loan and only applies the change.
@param loan Loan to compute interest
@param timestamp Target absolute unix time to calculate interest.
*/
function internalAddInterest(Loan storage loan, uint256 timestamp) internal {
if (timestamp > loan.interestTimestamp) {
uint256 newInterest = loan.interest;
uint256 newPunitoryInterest = loan.punitoryInterest;
uint256 newTimestamp;
uint256 realDelta;
uint256 calculatedInterest;
uint256 deltaTime;
uint256 pending;
uint256 endNonPunitory = min(timestamp, loan.dueTime);
if (endNonPunitory > loan.interestTimestamp) {
deltaTime = endNonPunitory - loan.interestTimestamp;
if (loan.paid < loan.amount) {
pending = loan.amount - loan.paid;
} else {
pending = 0;
}
(realDelta, calculatedInterest) = calculateInterest(deltaTime, loan.interestRate, pending);
newInterest = safeAdd(calculatedInterest, newInterest);
newTimestamp = loan.interestTimestamp + realDelta;
}
if (timestamp > loan.dueTime) {
uint256 startPunitory = max(loan.dueTime, loan.interestTimestamp);
deltaTime = timestamp - startPunitory;
uint256 debt = safeAdd(loan.amount, newInterest);
pending = min(debt, safeSubtract(safeAdd(debt, newPunitoryInterest), loan.paid));
(realDelta, calculatedInterest) = calculateInterest(deltaTime, loan.interestRatePunitory, pending);
newPunitoryInterest = safeAdd(newPunitoryInterest, calculatedInterest);
newTimestamp = startPunitory + realDelta;
}
if (newInterest != loan.interest || newPunitoryInterest != loan.punitoryInterest) {
loan.interestTimestamp = newTimestamp;
loan.interest = newInterest;
loan.punitoryInterest = newPunitoryInterest;
}
}
}
/**
@notice Updates the loan accumulated interests up to the current Unix time.
@param index Index of the loan
@return true If the interest was updated
*/
function addInterest(uint index) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent);
internalAddInterest(loan, block.timestamp);
}
/**
@notice Pay loan
Does a payment of a given Loan, before performing the payment the accumulated
interest is computed and added to the total pending amount.
Before calling this function, the msg.sender must call the "approve" function on the RCN Token, specifying an amount
sufficient enough to pay the equivalent of the desired payment and the oracle fee.
If the paid pending amount equals zero, the loan changes status to "paid" and it is considered closed.
@dev Because it is difficult or even impossible to know in advance how much RCN are going to be spent on the
transaction*, we recommend performing the "approve" using an amount 5% superior to the wallet estimated
spending. If the RCN spent results to be less, the extra tokens are never debited from the msg.sender.
* The RCN rate can fluctuate on the same block, and it is impossible to know in advance the exact time of the
confirmation of the transaction.
@param index Index of the loan
@param _amount Amount to pay, specified in the loan currency; or in RCN if the loan has no oracle
@param _from The identity of the payer
@param oracleData Data required by the oracle to return the rate, the content of this field must be provided
by the url exposed in the url() method of the oracle.
@return true if the payment was executed successfully
*/
function pay(uint index, uint256 _amount, address _from, bytes oracleData) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent);
addInterest(index);
uint256 toPay = min(getPendingAmount(index), _amount);
PartialPayment(index, msg.sender, _from, toPay);
loan.paid = safeAdd(loan.paid, toPay);
if (getRawPendingAmount(index) == 0) {
TotalPayment(index);
loan.status = Status.paid;
// ERC721, remove loan from circulation
lendersBalance[loan.lender] -= 1;
activeLoans -= 1;
Transfer(loan.lender, 0x0, index);
}
uint256 transferValue = convertRate(loan.oracle, loan.currency, oracleData, toPay);
require(transferValue > 0 || toPay < _amount);
lockTokens(rcn, transferValue);
require(rcn.transferFrom(msg.sender, this, transferValue));
loan.lenderBalance = safeAdd(transferValue, loan.lenderBalance);
return true;
}
/**
@notice Converts an amount to RCN using the loan oracle.
@dev If the loan has no oracle the currency must be RCN so the rate is 1
@return The result of the convertion
*/
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) public returns (uint256) {
if (oracle == address(0)) {
return amount;
} else {
uint256 rate;
uint256 decimals;
(rate, decimals) = oracle.getRate(currency, data);
require(decimals <= RCN_DECIMALS);
return (safeMult(safeMult(amount, rate), (10**(RCN_DECIMALS-decimals)))) / PRECISION;
}
}
/**
@notice Withdraw lender funds
When a loan is paid, the funds are not transferred automatically to the lender, the funds are stored on the
engine contract, and the lender must call this function specifying the amount desired to transfer and the
destination.
@dev This behavior is defined to allow the temporary transfer of the loan to a smart contract, without worrying that
the contract will receive tokens that are not traceable; and it allows the development of decentralized
autonomous organizations.
@param index Index of the loan
@param to Destination of the wiwthdraw funds
@param amount Amount to withdraw, in RCN
@return true if the withdraw was executed successfully
*/
function withdrawal(uint index, address to, uint256 amount) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender);
loan.lenderBalance = safeSubtract(loan.lenderBalance, amount);
require(rcn.transfer(to, amount));
unlockTokens(rcn, amount);
return true;
}
/**
@notice Withdraw lender funds in batch, it walks by all the loans passed to the function and withdraws all
the funds stored on that loans.
@dev This batch withdraw method can be expensive in gas, it must be used with care.
@param loanIds Array of the loans to withdraw
@param to Destination of the tokens
@return the total withdrawed
*/
function withdrawalList(uint256[] memory loanIds, address to) public returns (uint256) {
uint256 inputId;
uint256 totalWithdraw = 0;
for (inputId = 0; inputId < loanIds.length; inputId++) {
Loan storage loan = loans[loanIds[inputId]];
if (loan.lender == msg.sender) {
totalWithdraw += loan.lenderBalance;
loan.lenderBalance = 0;
}
}
require(rcn.transfer(to, totalWithdraw));
unlockTokens(rcn, totalWithdraw);
return totalWithdraw;
}
/**
@dev Deprecates the engine, locks the creation of new loans.
*/
function setDeprecated(bool _deprecated) public onlyOwner {
deprecated = _deprecated;
}
} | The loan 0 is a Invalid loan | function NanoLoanEngine(Token _rcn) public {
owner = msg.sender;
rcn = _rcn;
loans.length++;
}
| 5,714,142 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "hardhat/console.sol"; // dev & testing
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./ProjectERC20.sol";
import "./IContractRegistry.sol";
import "./IBatchCollection.sol";
import "./ProjectCollection.sol";
library uintConversion {
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
// Project-Vintage ERC20 Factory contract for BatchNFT fractionalization
// Locks in received ERC721 BatchNFTs and can mint corresponding quantity of ERC20s
// Permissionless, anyone can deploy new ERC20s unless they do not yet exist and pid exists
contract ProjectERC20Factory {
event TokenCreated(address tokenAddress);
address public contractRegistry;
address[] private deployedContracts; // Probably obsolete, moved to registry
mapping (string => address) public pContractRegistry;
constructor (address _contractRegistry) {
contractRegistry = _contractRegistry;
}
// Function to deploy new pERC20s
// Note: Function could be internal, but that would disallow pre-deploying ERC20s without existing NFTs
function deployNewToken(
string memory pvId,
string memory projectId,
uint16 vintage,
address _contractRegistry)
public {
require(!checkExistence(pvId), "pERC20 already exists");
address c = IContractRegistry(contractRegistry).projectCollectionAddress();
require(ProjectCollection(c).projectIds(projectId)==true, "Project does not yet exist");
string memory standard;
string memory methodology;
string memory region;
(standard, methodology, region) = ProjectCollection(c).getProjectDataByProjectId(projectId);
// Todo: Needs some consideration about automatic naming
ProjectERC20 t = new ProjectERC20(pvId, pvId, projectId, vintage, standard, methodology, region, _contractRegistry);
// Register deployed ERC20 in ContractRegistry
IContractRegistry(contractRegistry).addERC20(address(t));
// Move registration to ContractRegistry
deployedContracts.push(address(t));
pContractRegistry[pvId] = address(t);
emit TokenCreated(address(t));
}
// Deploy providing a BatchNFT as template, currently would work only with one single collection
function deployFromTemplate(uint256 tokenId) public {
// console.log("DEBUG: deploying from template");
address collection = IContractRegistry(contractRegistry).batchCollectionAddress();
(string memory pid, uint16 vintage, , , ) = IBatchCollection(collection).getBatchNFTData(tokenId);
string memory pvId = projectVintageId(pid, uintConversion.uint2str(vintage));
require(!checkExistence(pvId), "pERC20 already exists");
deployNewToken(pvId, pid, vintage, contractRegistry);
}
// Helper function to create unique project-vintage identifying string
function projectVintageId(string memory pid, string memory vintage)
internal pure returns (string memory) {
return string(abi.encodePacked(pid, vintage));
}
// Checks if same pToken has already been deployed
function checkExistence(string memory _pTokenIdentifier) internal view returns (bool) {
if (pContractRegistry[_pTokenIdentifier] == address(0)) {
// console.log("DEBUG: checkExistence: false");
return false;
}
else {
// console.log("DEBUG: checkExistence: true");
return true;
}
}
// Lists addresses of deployed contracts
function getContracts() public view returns (address[] memory) {
for (uint256 i = 0; i < deployedContracts.length; i++) {
// console.log("DEBUG sol: logging contract",i, deployedContracts[i]);
}
return deployedContracts;
}
}
| Lists addresses of deployed contracts console.log("DEBUG sol: logging contract",i, deployedContracts[i]); | function getContracts() public view returns (address[] memory) {
for (uint256 i = 0; i < deployedContracts.length; i++) {
}
return deployedContracts;
}
| 5,400,322 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
/* EXTERNAL DEPENDENCIES */
import "@openzeppelin/contracts/access/Ownable.sol";
/* INTERNAL DEPENDENCIES */
import "./CommonStructs.sol";
/**
* @title Instructions contract
* @notice This contract is responsible for storing the dynamic instructions defined by the contract owner.
*/
/**
An instruction has:
- a type that determine which parameters it accepts
- a signature that is used for the low level .call()
- a name that is used as a key to select an instruction uniquely
*/
contract Instructions is Ownable {
/* STORAGE VARIABLES */
/// @dev Mapping between instruction name used in deals Articles and instruction signature used in low level .call()
mapping (string => string) private instructionsSignature;
/// @dev Mapping between instruction name and its type which determines how the Interpreter will run an Article
mapping (string => CommonStructs.InstructionTypes) private instructionsType;
/* EVENTS */
/**
* @dev Event emitted when an new instruction is added/supported
* @param _instructionName Name of the instruction, for ex: "IF-ADDR"
* @param _instructionType Type of the instruction, for ex: "ADDRESS_ADDRESS_R_BOOL"
* @param _instructionSignature Signature of the instruction, for ex: "_ifAddress(address, address)"
*/
event AddInstruction(string _instructionName, CommonStructs.InstructionTypes _instructionType, string _instructionSignature);
/* PUBLIC INTERFACE */
/**
* @dev Returns an instruction type and signature based on its name
* @param _instructionName Name of the instruction, for ex: "IF-ADDR"
*/
function getInstruction(string memory _instructionName) public view returns(CommonStructs.InstructionTypes, string memory) {
return (instructionsType[_instructionName], instructionsSignature[_instructionName]);
}
/**
* @dev Add an instruction to the list of supported instructions (onlyOwner)
* @param _instructionName Name of the instruction, for ex: "IF-ADDR"
* @param _instructionType Type of the instruction, for ex: "ADDRESS_ADDRESS_R_BOOL"
* @param _instructionSignature Signature of the instruction, for ex: "_ifAddress(address, address)"
*/
function addInstruction(
string memory _instructionName,
CommonStructs.InstructionTypes _instructionType,
string memory _instructionSignature
)
public onlyOwner {
instructionsType[_instructionName] = CommonStructs.InstructionTypes(_instructionType);
instructionsSignature[_instructionName] = _instructionSignature;
emit AddInstruction(_instructionName, _instructionType, _instructionSignature);
}
/* OVERRIDE & BLOCK UNUSED INHERITED FUNCTIONS */
/**
* @dev Block OpenZeppelin Ownable.renounceOwnership
* @notice Will always revert
*/
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
}
| Add an instruction to the list of supported instructions (onlyOwner) _instructionName Name of the instruction, for ex: "IF-ADDR" _instructionType Type of the instruction, for ex: "ADDRESS_ADDRESS_R_BOOL" _instructionSignature Signature of the instruction, for ex: "_ifAddress(address, address)"/ | function addInstruction(
string memory _instructionName,
CommonStructs.InstructionTypes _instructionType,
string memory _instructionSignature
)
public onlyOwner {
instructionsType[_instructionName] = CommonStructs.InstructionTypes(_instructionType);
instructionsSignature[_instructionName] = _instructionSignature;
emit AddInstruction(_instructionName, _instructionType, _instructionSignature);
}
| 12,939,789 |
/**
*Submitted for verification at Etherscan.io on 2020-09-04
*/
pragma solidity ^0.6.0;
// "SPDX-License-Identifier: UNLICENSED "
// ----------------------------------------------------------------------------
// 'The Forms ver.2' token contract
// Symbol : FRMS
// Name : The Forms
// Total supply: 5,898,277
// Decimals : 18
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
//assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
//assert(c >= a);
return c;
}
function ceil(uint a, uint m) internal pure returns (uint r) {
return (a + m - 1) / m * m;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
abstract contract ERC20Interface {
function totalSupply() public virtual view returns (uint);
function balanceOf(address tokenOwner) public virtual view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public virtual returns (bool success);
function approve(address spender, uint256 tokens) public virtual returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Token is ERC20Interface, Owned {
using SafeMath for uint256;
string public symbol = "FRMS";
string public name = "The Forms";
uint256 public decimals = 18;
uint256 private _totalSupply = 5898277 * 10 ** (decimals);
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
address constant private TEAM = 0x24B73DC219196a5E373D73b7Cd638017f1f07E2F;
address constant private MARKETING_FUNDS = 0x4B63B18b66Fc617B5A3125F0ABB565Dc22d732ba ;
address constant private COMMUNITY_REWARD = 0xC071C603238F387E48Ee96826a81D608e304545A;
address constant private PRIVATE_SALE_ADD1 = 0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd;
address constant private PRIVATE_SALE_ADD2 = 0x8f63Fe51A3677cf02C80c11933De4B5846f2a336;
address constant private PRIVATE_SALE_ADD3 = 0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1;
struct LOCKING{
uint256 lockedTokens; //DR , //PRC
uint256 releasePeriod;
uint256 cliff; //DR, PRC
uint256 lastVisit;
uint256 releasePercentage;
bool directRelease; //DR
}
mapping(address => LOCKING) public walletsLocking;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
owner = 0xA6a3E445E613FF022a3001091C7bE274B6a409B0;
_tokenAllocation();
_setLocking();
saleOneAllocationsLocking();
saleTwoAllocationsLocking();
saleThreeAllocations();
}
function _tokenAllocation() private {
// send funds to team
_allocate(TEAM, 1303625 );
// send funds to community reward
_allocate(COMMUNITY_REWARD,1117393 );
// send funds to marketing funds
_allocate(MARKETING_FUNDS, 964572);
// send funds to owner for uniswap liquidity
_allocate(owner, 354167 );
// Send to private sale addresses 1
_allocate(0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd, 529131);
// Send to private sale addresses 2
_allocate(0x8f63Fe51A3677cf02C80c11933De4B5846f2a336, 242718 );
// Send to private sale addresses 3
_allocate(0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1, 252427 );
}
function _setLocking() private{
//////////////////////////////////TEAM////////////////////////////////////
walletsLocking[TEAM].directRelease = true;
walletsLocking[TEAM].lockedTokens = 1303625 * 10 ** (decimals);
walletsLocking[TEAM].cliff = block.timestamp.add(365 days);
//////////////////////////////////PRIVATE SALE ADDRESS 1////////////////////////////////////
/////////////////////////////0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd////////////////////
walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].directRelease = true;
walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].lockedTokens = 529131 * 10 ** (decimals);
walletsLocking[0xB5Aceaa4db96d6901b492505170Ab7F1d6E7cdAd].cliff = block.timestamp.add(180 days);
//////////////////////////////////PRIVATE SALE ADDRESS 2////////////////////////////////////
/////////////////////////////0x8f63Fe51A3677cf02C80c11933De4B5846f2a336////////////////////
walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].directRelease = true;
walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].lockedTokens = 242718 * 10 ** (decimals);
walletsLocking[0x8f63Fe51A3677cf02C80c11933De4B5846f2a336].cliff = block.timestamp.add(180 days);
//////////////////////////////////PRIVATE SALE ADDRESS 3////////////////////////////////////
/////////////////////////////0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1////////////////////
walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].directRelease = true;
walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].lockedTokens = 252427 * 10 ** (decimals);
walletsLocking[0x134D97378Ed04eC0CaE4C689800Be9e96D683ac1].cliff = block.timestamp.add(180 days);
//////////////////////////////////COMMUNITY_REWARD////////////////////////////////////
walletsLocking[COMMUNITY_REWARD].directRelease = false;
walletsLocking[COMMUNITY_REWARD].lockedTokens = 1117393 * 10 ** (decimals);
walletsLocking[COMMUNITY_REWARD].cliff = block.timestamp.add(30 days);
walletsLocking[COMMUNITY_REWARD].lastVisit = block.timestamp.add(30 days);
walletsLocking[COMMUNITY_REWARD].releasePeriod = 30 days; // 1 month
walletsLocking[COMMUNITY_REWARD].releasePercentage = 5586965e16; // 55869.65
//////////////////////////////////MARKETING_FUNDS////////////////////////////////////
walletsLocking[MARKETING_FUNDS].directRelease = false;
walletsLocking[MARKETING_FUNDS].lockedTokens = 7716576e17; // 771657.6
walletsLocking[MARKETING_FUNDS].cliff = block.timestamp;
walletsLocking[MARKETING_FUNDS].lastVisit = block.timestamp;
walletsLocking[MARKETING_FUNDS].releasePeriod = 30 days; // 1 month
walletsLocking[MARKETING_FUNDS].releasePercentage = 1929144e17; // 192914.4
}
function saleThreeAllocations() private {
_allocate(0x2488f090656BddB63fe3Bdb506D0D109AaaD93Bb,58590);
_allocate(0xD7a98d34CD49dd203cAc9752Ea400Ee309A5F602,46872 );
_allocate(0x7b88aD278Cd11506661516E544EcAA9e39F03aF0,39060 );
_allocate(0xc77c3EfB55bd7b0E44c13EB27eb33c98597f0a68,39060 );
_allocate(0x42D455B219214FDA88aF47786CC6e3B5f9a19c37,27342 );
_allocate(0x42D455B219214FDA88aF47786CC6e3B5f9a19c37,19530 );
_allocate(0x42D455B219214FDA88aF47786CC6e3B5f9a19c37,19530 );
_allocate(0xd4Bc360cFDd35e8025dA8237A49D80Fdfb8E351e,17577 );
_allocate(0x707D048708802Dc7730C722F8886105Ff07f0331,15624 );
_allocate(0xfcd987b0D6656c1c84EF73da18c6596D42a73c5E,15624 );
_allocate(0xa38B4f096Ef6323736D26BF6F9a9Ce1dd2257732,15624 );
_allocate(0x4b1bA9aA4337e65ffA2155b92BaFd8E177E73CB5,11718 );
_allocate(0xE8E61Db7918bD88E5ff764Ad5393e87D7AaEf9aD,11718 );
_allocate(0x28B7677b86be88d432775f1c808a33957f6833BE,11718 );
_allocate(0x65E27aD821D14E3567E97eb600728d2AAc7e1be4,11718 );
_allocate(0xDa892C1700147079d0bDeafB7b566E77315f98A4,11718 );
_allocate(0xb0B743639224d2c82c857E6a504daA207e385Dba,8203 );
_allocate(0xfce0413BAD4E59f55946669E678EccFe87777777,7812 );
_allocate(0x78782592D452e92fFFAB8e145201108e97cE36b6,7812 );
_allocate(0x78782592D452e92fFFAB8e145201108e97cE36b6,7812 );
_allocate(0x1e36795b5168E574b6EF0f0461CC4026251C533E,7812 );
_allocate(0x81aA6141923Ea42fCAa763d9857418224d9b025a,7812 );
_allocate(0xf470bbfeaB9B0d60e21FBd611C5d569df20704CE,7812 );
_allocate(0x31E985b4f7af6B479148d260309B7BcEcEF0fa7B,7812 );
_allocate(0x707D048708802Dc7730C722F8886105Ff07f0331,7812 );
_allocate(0xf2d2a2831f411F5cE863E8f836481dB0b40c03A5,7812 );
_allocate(0x716C9cC35607040f54b9232D35a2871F46894F58,6000 );
_allocate(0x81724bCe3D755AEB716d030cbD2c0f5b9f508Df0,5000 );
_allocate(0xE8CC2a8540C7339430859b8E7902AF2fE2d91865,4687 );
_allocate(0x268e1fEE56498Cc24758864AA092F870e8220f74,3906 );
_allocate(0xF93eD4Fe97eB8A2508D03222a28E332F1C89B0eD,3906 );
_allocate(0x65E27aD821D14E3567E97eb600728d2AAc7e1be4,3906 );
_allocate(0x001C88d92d199C9EB936Ed3D6758da7C48e4D08e,3906 );
_allocate(0x42c6Be1400578B238aCd8946FE9682E650DfdE8D,3906 );
_allocate(0x65E27aD821D14E3567E97eb600728d2AAc7e1be4,3906 );
_allocate(0xAcb272Eac895FA57394747615fCb068b8858AAF2,3906 );
_allocate(0x21eDE22Cb8Ab64F4F74128f3D0250a7851971A33,3906 );
_allocate(0x3DFf997410D94E2E3C961F805b85eB2Ef80622c5,3906 );
_allocate(0x8F70b3aC45A6896532FB90B992D5B7827bA88d3C,3906 );
_allocate(0xef6D6a51900B5cf220Fe54F8309B6Eda32e794E9,3906 );
_allocate(0x52BF55C77C402F90dF3Bc1d9E6a0faf262437ab1,3906 );
_allocate(0xa2639Ef1e7956b242E2C5Ac87b72B077FEbe2783,3906 );
_allocate(0x716C9cC35607040f54b9232D35a2871F46894F58,3906 );
_allocate(0x5826914A6223053038328ab3bc7CEB64db04DDc4,3515 );
_allocate(0x896Fa945c5533631F8DaFE7483FeA6859537cfD0,3125 );
_allocate(0x2d5304bA4f2c6EFF5D53CecF64AF89818A416cB9,3125 );
_allocate(0xD53354D4Fb7BcE81Cd4F83c457dbd5EF655C9E93,2734 );
_allocate(0x49216a6434B75051e9063E99Bb486bc85B0b0605,1953 );
_allocate(0xD53354D4Fb7BcE81Cd4F83c457dbd5EF655C9E93,1953 );
_allocate(0x4CEa5d86Bb0bBFa77CB452CCBD52e76dEA4dE045,1627 );
_allocate(0xC274362c1E85834Eb8387C18168C01aaEe2B00d7,1562 );
_allocate(0x18A8e216c3406dED40438856B45198B3ce39e522,1367 );
_allocate(0x51B3954e185869FB4cb9D2Bf9Fbd00A22900E800,477 );
}
function saleOneAllocationsLocking() private {
uint256 lockingPeriod = 24 hours;
_allocateLock(0xCCa178a04D83Af193330C7927fb9a42212Fb1C25, 85932, lockingPeriod);
_allocateLock(0xD7d7d68E4BDCf85c073485aB7Bfd151B0C019F1F, 39060, lockingPeriod);
_allocateLock(0xf470bbfeaB9B0d60e21FBd611C5d569df20704CE, 31248, lockingPeriod);
_allocateLock(0x9022BC8774AebC343De33423570b5285981bd9E1, 31248, lockingPeriod);
_allocateLock(0xcf9Bb70b2f1aCCb846e8B0C665a1Ab5D5D35cA05, 31248, lockingPeriod);
_allocateLock(0xfce0413BAD4E59f55946669E678EccFe87777777, 23436, lockingPeriod);
_allocateLock(0xf470bbfeaB9B0d60e21FBd611C5d569df20704CE, 23436, lockingPeriod);
_allocateLock(0xfEeA4Cd7a96dCffBDc6d2e6c814eb4544ab62667, 23436, lockingPeriod);
_allocateLock(0xb4A0563DE6ABeE9C3C0631FbAE3444F012a40dB5, 19530, lockingPeriod);
_allocateLock(0x54a9bB530474d287202Da7f4d5c9756E13f699f3, 15624, lockingPeriod);
_allocateLock(0xEad249D58E4ebbFBf4ABbeCc1201bD88E50f7967, 15624, lockingPeriod);
_allocateLock(0x3Dd4234DaeefBaBCeAA6068C04C3f75F19aa2cdA, 15624, lockingPeriod);
_allocateLock(0x88F7541D87b7f3c88115A5b2387587263c5d4C7E, 11718, lockingPeriod);
_allocateLock(0xf3e4D991a20043b6Bd025058CF4d96Fd7501070b, 11718, lockingPeriod);
_allocateLock(0xEc315068A71458FB1A6cC063E9BC7369EC41a7a5, 8593, lockingPeriod);
_allocateLock(0x54a9bB530474d287202Da7f4d5c9756E13f699f3, 7812, lockingPeriod);
_allocateLock(0x0fEB352cfd10314af9abCF4eD03Da9311Bf8bC44, 7812, lockingPeriod);
_allocateLock(0xd28932b8d4Be295D4B90b514EFa3E80436d66bEC, 7812, lockingPeriod);
_allocateLock(0x268e1fEE56498Cc24758864AA092F870e8220f74, 7812, lockingPeriod);
_allocateLock(0xDFF214084Fee648c8e0bc0838C1fa5E8548F58aC, 7812, lockingPeriod);
_allocateLock(0x4356DdB30910c1f9b3Aa1e6A60111CE9802B6dF9, 7812, lockingPeriod);
_allocateLock(0x863A3bD6f28f4F4A131c88708dA91076fDC362C7, 7812, lockingPeriod);
_allocateLock(0x3F79B63823E435FaF08A95e0973b389333B19b99, 7812, lockingPeriod);
_allocateLock(0x8F70b3aC45A6896532FB90B992D5B7827bA88d3C, 7812, lockingPeriod);
_allocateLock(0xEc315068A71458FB1A6cC063E9BC7369EC41a7a5, 6640, lockingPeriod);
_allocateLock(0x138EcD97Da1C9484263BfADDc1f3D6AE2a435bCb, 6250, lockingPeriod);
_allocateLock(0x53A07d3c1Fdc58c0Cfd2c96817D9537A9E113dd4, 5468, lockingPeriod);
_allocateLock(0xCEC0971e55A4C39e3e2C4d8f175CC6e53c138B0A, 4297, lockingPeriod);
_allocateLock(0xBA682E593784f7654e4F92D58213dc495f229Eec, 3906, lockingPeriod);
_allocateLock(0x9B9e35C223B39f908A036E41011D9E3aDb06ae0B, 3906, lockingPeriod);
_allocateLock(0xBA98b69a140c078746219D0bBf0bb3b923483374, 3906, lockingPeriod);
_allocateLock(0x34c4E14243a95b148534f894FCe86c61bC9F731a, 3906, lockingPeriod);
_allocateLock(0x9A61567A3e3c5b47DFFB0670C629A40533Eb84d5, 3906, lockingPeriod);
_allocateLock(0xda90dDbbdd4e0237C6889367c1556179c817680B, 3567, lockingPeriod);
_allocateLock(0x329318Ca294A2d127e43058A7b23ED514B503d76, 2734, lockingPeriod);
_allocateLock(0x7B3fC9597f146F0A80FC26dB0DdF62C04ea89740, 2578, lockingPeriod);
_allocateLock(0xb6eC0d0172BC4Cff8fF669b543e03c2c8B64Fc5E, 2344, lockingPeriod);
_allocateLock(0x53A07d3c1Fdc58c0Cfd2c96817D9537A9E113dd4, 2344, lockingPeriod);
}
function saleTwoAllocationsLocking() private {
uint256 lockingPeriod = 12 hours;
_allocateLock(0xc77c3EfB55bd7b0E44c13EB27eb33c98597f0a68, 16758, lockingPeriod);
_allocateLock(0x9E817382A12D2b1D15246c4d383bEB8171BCdfA9, 13965, lockingPeriod);
_allocateLock(0xfF6735CFf3DFED5d68dC3DbeBb0d34c5e815BA09, 11172, lockingPeriod);
_allocateLock(0x5400087152e436C7C22883d01911868A3C892551, 7820, lockingPeriod);
_allocateLock(0x974896E96219Dd508100f2Ad58921290655072aD, 5586, lockingPeriod);
_allocateLock(0x0fEB352cfd10314af9abCF4eD03Da9311Bf8bC44, 5586, lockingPeriod);
_allocateLock(0x268e1fEE56498Cc24758864AA092F870e8220f74, 5586, lockingPeriod);
_allocateLock(0xC274362c1E85834Eb8387C18168C01aaEe2B00d7, 4469, lockingPeriod);
_allocateLock(0x93935316db093A8665E91EE932591F76bf8E5295, 3631, lockingPeriod);
_allocateLock(0x8bdBF4B19cb840e9Ac9B1eFFc2BfAd47591B5bF2, 2793, lockingPeriod);
}
function _allocateLock(address user, uint256 tokens, uint256 lockingPeriod) private{
uint256 startTime = 1599253200; // 4 sep
walletsLocking[user].directRelease = true;
walletsLocking[user].lockedTokens = tokens * 10 ** (decimals);
walletsLocking[user].cliff = startTime.add(lockingPeriod);
_allocate(user, tokens);
}
function _allocate(address user, uint256 tokens) private {
balances[user] = balances[user].add(tokens * 10 ** (decimals));
emit Transfer(address(0),user, tokens * 10 ** (decimals));
}
/** ERC20Interface function's implementation **/
function totalSupply() public override view returns (uint256){
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint256 balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint256 tokens) public override returns (bool success) {
// prevent transfer to 0x0, use burn instead
require(address(to) != address(0), "Transfer to address 0 not allowed");
require(balances[msg.sender] >= tokens, "SENDER: insufficient balance");
if (walletsLocking[msg.sender].lockedTokens > 0 ){
if(walletsLocking[msg.sender].directRelease)
directRelease(msg.sender);
else
checkTime(msg.sender);
}
require(balances[msg.sender].sub(tokens) >= walletsLocking[msg.sender].lockedTokens, "Please wait for tokens to be released");
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
// ------------------------------------------------------------------------
function approve(address spender, uint256 tokens) public override returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender,spender,tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){
require(tokens <= allowed[from][msg.sender]); //check allowance
// prevent transfer to 0x0, use burn instead
require(address(to) != address(0), "Transfer to address 0 not allowed");
require(address(from) != address(0), "Transfer from address 0 not allowed");
require(balances[from] >= tokens, "SENDER: Insufficient balance");
if (walletsLocking[from].lockedTokens > 0){
if(walletsLocking[from].directRelease)
directRelease(from);
else
checkTime(from);
}
require(balances[from].sub(tokens) >= walletsLocking[from].lockedTokens, "Please wait for tokens to be released");
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from,to,tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// @dev Internal function that burns an amount of the token from a given account
// @param _amount The amount that will be burnt
// @param _account The tokens to burn from
// can be used from account owner or contract owner
// ------------------------------------------------------------------------
function burnTokens(uint256 _amount, address _account) public {
require(msg.sender == _account || msg.sender == owner, "UnAuthorized");
require(balances[_account] >= _amount, "Insufficient account balance");
_totalSupply = _totalSupply.sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
balances[_account] = balances[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
function directRelease(address _wallet) private{
if(block.timestamp > walletsLocking[_wallet].cliff){
walletsLocking[_wallet].lockedTokens = 0;
}
}
function checkTime(address _wallet) private {
// if cliff is applied
if(block.timestamp > walletsLocking[_wallet].cliff){
uint256 timeSpanned = (now.sub(walletsLocking[_wallet].lastVisit)).div(walletsLocking[_wallet].releasePeriod);
// if release period is passed
if (timeSpanned >= 1){
uint256 released = timeSpanned.mul(walletsLocking[_wallet].releasePercentage);
if (released > walletsLocking[_wallet].lockedTokens){
released = walletsLocking[_wallet].lockedTokens;
}
walletsLocking[_wallet].lastVisit = now;
walletsLocking[_wallet].lockedTokens = walletsLocking[_wallet].lockedTokens.sub(released);
}
}
}
} | ------------------------------------------------------------------------ Internal function that burns an amount of the token from a given account _amount The amount that will be burnt _account The tokens to burn from can be used from account owner or contract owner ------------------------------------------------------------------------ | function burnTokens(uint256 _amount, address _account) public {
require(msg.sender == _account || msg.sender == owner, "UnAuthorized");
require(balances[_account] >= _amount, "Insufficient account balance");
balances[_account] = balances[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
| 945,351 |
./partial_match/1/0x97eD948251a5741611d2a6b9D7136782911Ff807/sources/contracts/custody/ENSCustody.sol | This handles the situation when minting a ERC1155 directly to custody, as well as when wrapping a ERC721 token | function onERC1155Received(
address,
address from,
uint256 tokenId,
uint256,
bytes calldata
) public override onlyNameWrapper returns (bytes4) {
if (from != address(0)) {
_park(tokenId, from);
}
return this.onERC1155Received.selector;
}
| 2,673,479 |
./full_match/5/0x9d45d05494eD6E8964a3818E506C8488a4FEBb82/sources/Users/seb/repo/hunt/neverlose/contract/contracts/WRNRewardPool.sol | Total of 1.2M WRN tokens will be distributed for 3.6 years - 0.5 WRN per block for beta users (early participants) - 0.1 WRN per block after the bonus period rewardBlocks = 8,800,000, bonusBlocks = 500,000 -> 500,000 0.5 + 8,300,000 0.1 = 1,080,000 (distribution) + 1,080,000 / 9 = 120,000 (dev pool) 5x distribution for the first 500k blocks (appx 75 days) | function initialize(address WRNAddress, uint256 rewardStartBlock, uint256 rewardBlocks, uint256 bonusBlocks) public initializer {
require(bonusBlocks <= rewardBlocks, 'INVALID_PARAM');
LockUpPool.initialize();
WRNToken = ERC20PresetMinterPauserUpgradeSafe(WRNAddress);
REWARD_START_BLOCK = rewardStartBlock;
REWARD_EARLY_BONUS_END_BLOCK = REWARD_START_BLOCK.add(bonusBlocks);
REWARD_EARLY_BONUS_BOOST = 5;
}
| 1,953,363 |
./full_match/137/0xc8F7b50EDE4AcEF9845B52589aC298ff88284B55/sources/project_/contracts/polygon/Demo.sol | ========== 2. addStake ========== / 這裡要改成傳值 bytes32 _game = 0x3434313463323763613161363636653739646635643263383464393466373362; store on chain stakeSelection[msg.sender] = _win; / 這個不用存儲應該沒事吧 / trigger event ========== usage: record user's stake to home/away prize pool ========== / ========== usage: add user to home/away address list ========== / add user's wallet to home address list record user's stake increase home's pool value | function addStake(bytes32 _hash, string memory _win) public payable {
require(msg.value > 0, "You must send some ether to add a message.");
stakeHash[_hash] = msg.sender;
if ( inputValue == keccak256(abi.encodePacked("home")) ) {
punterHome.push(payable(msg.sender));
stakeHome[msg.sender] += msg.value;
stakesHome += msg.value;
punterAway.push(payable(msg.sender));
stakeAway[msg.sender] += msg.value;
stakesAway += msg.value;
}
}
| 4,718,355 |
pragma solidity ^0.5.2;
import "./absn.sol";
library map {
using absn for absn.Proposal;
// Iterable map of (address => Proposal)
// index = ordinals[a]-1
// keys[index].maker = a
using map for ProposalMap;
struct ProposalMap {
address[] keys;
mapping (address => uint) ordinals; // map the proposal's maker to (its index + 1)
mapping (address => absn.Proposal) vals; // maker => proposal
}
function count(ProposalMap storage this) internal view returns (uint) {
return this.keys.length;
}
function getKey(ProposalMap storage this, uint index) internal view returns (address) {
return this.keys[index];
}
function get(ProposalMap storage this, uint index) internal view returns (absn.Proposal storage) {
address key = this.getKey(index);
return this.vals[key];
}
function get(ProposalMap storage this, address maker) internal view returns (absn.Proposal storage) {
return this.vals[maker];
}
function has(ProposalMap storage this, address maker) internal view returns (bool) {
return this.ordinals[maker] > 0;
}
function push(ProposalMap storage this, absn.Proposal memory proposal) internal returns (absn.Proposal storage) {
address key = proposal.maker;
uint ordinal = this.ordinals[key];
require (ordinal == 0, "maker already has a proposal");
this.vals[key] = proposal;
this.ordinals[key] = this.keys.push(key);
return this.vals[key];
}
function remove(ProposalMap storage this, address maker) internal returns (bool success) {
uint ordinal = this.ordinals[maker];
require(ordinal > 0, "key not exist");
this.remove(ordinal-1, maker);
return true;
}
// index is the correct array index, which is (set.ordinals[item]-1)
function remove(ProposalMap storage this, uint index) internal {
address key = this.keys[index];
require(key != address(0x0), "index not exist");
this.remove(index, key);
}
// @require keys[index] == maker
function remove(ProposalMap storage this, uint index, address maker) internal {
delete this.ordinals[maker];
delete this.vals[maker];
if (this.keys.length-1 != index) {
// swap with the last item in the keys and delete it
this.keys[index] = this.keys[this.keys.length-1];
this.ordinals[this.keys[index]] = index + 1;
}
// delete the last item from the array
this.keys.length--;
}
function clear(ProposalMap storage this) internal {
for (uint i = 0; i < this.keys.length; i++) {
address key = this.keys[i];
delete this.ordinals[key];
delete this.vals[key];
}
delete this.keys;
}
///////////////////////////////////////////////////////////////////////
// Iterable map of (address => bool)
// index = ordinals[a]-1
// keys[index] = a
using map for AddressBool;
struct AddressBool {
address[] keys;
mapping (address => uint) ordinals; // map the voter's adress to (its index + 1)
mapping (address => bool) vals;
}
function count(AddressBool storage this) internal view returns (uint) {
return this.keys.length;
}
function getKey(AddressBool storage this, uint index) internal view returns (address) {
return this.keys[index];
}
function get(AddressBool storage this, uint index) internal view returns (address, bool) {
address key = this.getKey(index);
return (key, this.vals[key]);
}
function get(AddressBool storage this, address key) internal view returns (bool) {
return this.vals[key];
}
function has(AddressBool storage this, address key) internal view returns (bool) {
return this.ordinals[key] > 0;
}
/**
* @return true if new (key,val) is added, false if old key is map to a new value
*/
function set(AddressBool storage this, address key, bool val) internal returns (bool) {
this.vals[key] = val;
uint ordinal = this.ordinals[key];
if (ordinal == 0) {
this.ordinals[key] = this.keys.push(key);
return true;
}
if (ordinal > this.keys.length || this.keys[ordinal-1] != key) {
// storage inconsistency due to deleting proposal without clearing proposal.votes
this.ordinals[key] = this.keys.push(key);
return true;
}
// key already has a proposal
return false;
}
function remove(AddressBool storage this, address key) internal {
uint ordinal = this.ordinals[key];
require(ordinal > 0, "key not exist");
this.remove(ordinal-1, key);
}
function remove(AddressBool storage this, uint index) internal {
address key = this.keys[index];
require(key != address(0x0), "index not exist");
this.remove(index, key);
}
// @require keys[index] == key
function remove(AddressBool storage this, uint index, address key) internal {
delete this.ordinals[key];
delete this.vals[key];
if (this.keys.length-1 != index) {
// swap with the last item in the keys and delete it
this.keys[index] = this.keys[this.keys.length-1];
this.ordinals[this.keys[index]] = index + 1;
}
// delete the last item from the array
this.keys.length--;
}
function clear(AddressBool storage this) internal {
for (uint i = 0; i < this.keys.length; i++) {
address key = this.keys[i];
delete this.ordinals[key];
delete this.vals[key];
}
delete this.keys;
}
} | @require keys[index] == key swap with the last item in the keys and delete it | function remove(AddressBool storage this, uint index, address key) internal {
delete this.ordinals[key];
delete this.vals[key];
if (this.keys.length-1 != index) {
this.keys[index] = this.keys[this.keys.length-1];
this.ordinals[this.keys[index]] = index + 1;
}
}
| 2,521,136 |
pragma solidity ^0.4.24;
/// @title Raiden MicroTransfer Channels Contract.
contract RaidenMicroTransferChannels {
/*
* Data structures
*/
// The only role of the owner_address is to add or remove trusted contracts
address public owner_address;
// Number of blocks to wait from an uncooperativeClose initiated by the sender
// in order to give the receiver a chance to respond with a balance proof
// in case the sender cheats. After the challenge period, the sender can settle
// and delete the channel.
uint32 public challenge_period;
// Contract semantic version
string public constant version = '0.2.0';
// We temporarily limit total token deposits in a channel to 100 tokens with 18 decimals.
// This was calculated just for RDN with its current (as of 30/11/2017) price and should
// not be considered to be the same for other tokens.
// This is just for the bug bounty release, as a safety measure.
uint256 public constant channel_deposit_bugbounty_limit = 10 ** 18 * 100;
mapping (bytes32 => Channel) public channels;
mapping (bytes32 => ClosingRequest) public closing_requests;
mapping (address => bool) public trusted_contracts;
mapping (bytes32 => uint256) public withdrawn_balances;
// 24 bytes (deposit) + 4 bytes (block number)
struct Channel {
// uin256 size of the deposit
uint256 deposit;
// Block number at which the channel was opened. Used in creating
// a unique identifier for the channel between a sender and receiver.
// Supports creation of multiple channels between the 2 parties and prevents
// replay of messages in later channels.
uint32 open_block_number;
}
// 24 bytes (deposit) + 4 bytes (block number)
struct ClosingRequest {
// Number of tokens owed by the sender when closing the channel.
uint256 closing_balance;
// Block number at which the challenge period ends, in case it has been initiated.
uint32 settle_block_number;
}
/*
* Modifiers
*/
modifier isOwner() {
require(msg.sender == owner_address);
_;
}
modifier isTrustedContract() {
require(trusted_contracts[msg.sender]);
_;
}
/*
* Events
*/
event ChannelCreated(
address indexed _sender_address,
address indexed _receiver_address,
uint256 _deposit);
event ChannelToppedUp (
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _added_deposit);
event ChannelCloseRequested(
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _balance);
event ChannelSettled(
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _balance,
uint256 _receiver_tokens);
event ChannelWithdraw(
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _withdrawn_balance);
event TrustedContract(
address indexed _trusted_contract_address,
bool _trusted_status);
/*
* Constructor
*/
/// @notice Constructor for creating the uRaiden microtransfer channels contract.
/// @param _challenge_period A fixed number of blocks representing the challenge period.
/// We enforce a minimum of 500 blocks waiting period.
/// after a sender requests the closing of the channel without the receiver's signature.
/// @param _trusted_contracts Array of contract addresses that can be trusted to
/// open and top up channels on behalf of a sender.
constructor(
uint32 _challenge_period,
address[] _trusted_contracts)
public
{
require(_challenge_period >= 500);
challenge_period = _challenge_period;
owner_address = msg.sender;
addTrustedContracts(_trusted_contracts);
}
/*
* External functions
*/
/// @notice Creates a new channel between `msg.sender` and `_receiver_address` and transfers
/// the `_deposit` token deposit to this contract. Compatibility with ERC20 tokens.
/// @param _receiver_address The address that receives tokens.
function createChannel(address _receiver_address) external payable {
createChannelPrivate(msg.sender, _receiver_address, msg.value);
}
/// @notice Function that allows a delegate contract to create a new channel between
/// `_sender_address` and `_receiver_address` and transfers the token deposit to this contract.
/// Can only be called by a trusted contract. Compatibility with ERC20 tokens.
/// @param _sender_address The sender's address in behalf of whom the delegate sends tokens.
/// @param _receiver_address The address that receives tokens.
function createChannelDelegate(
address _sender_address,
address _receiver_address)
isTrustedContract
external
payable
{
createChannelPrivate(_sender_address, _receiver_address, msg.value);
}
/// @notice Increase the channel deposit with `_added_deposit`.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
function topUp(
address _receiver_address,
uint32 _open_block_number)
external
payable
{
updateInternalBalanceStructs(
msg.sender,
_receiver_address,
_open_block_number,
msg.value
);
}
/// @notice Function that allows a delegate contract to increase the channel deposit
/// with `_added_deposit`. Can only be called by a trusted contract. Compatibility with ERC20 tokens.
/// @param _sender_address The sender's address in behalf of whom the delegate sends tokens.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
function topUpDelegate(
address _sender_address,
address _receiver_address,
uint32 _open_block_number)
isTrustedContract
external
payable
{
updateInternalBalanceStructs(
_sender_address,
_receiver_address,
_open_block_number,
msg.value
);
}
/// @notice Allows channel receiver to withdraw tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _balance Partial or total amount of tokens owed by the sender to the receiver.
/// Has to be smaller or equal to the channel deposit. Has to match the balance value from
/// `_balance_msg_sig` - the balance message signed by the sender.
/// Has to be smaller or equal to the channel deposit.
/// @param _balance_msg_sig The balance message signed by the sender.
function withdraw(
uint32 _open_block_number,
uint256 _balance,
bytes _balance_msg_sig)
external
{
require(_balance > 0);
// Derive sender address from signed balance proof
address sender_address = extractBalanceProofSignature(
msg.sender,
_open_block_number,
_balance,
_balance_msg_sig
);
bytes32 key = getKey(sender_address, msg.sender, _open_block_number);
// Make sure the channel exists
require(channels[key].open_block_number > 0);
// Make sure the channel is not in the challenge period
require(closing_requests[key].settle_block_number == 0);
require(_balance <= channels[key].deposit);
require(withdrawn_balances[key] < _balance);
uint256 remaining_balance = _balance - withdrawn_balances[key];
withdrawn_balances[key] = _balance;
// Send the remaining balance to the receiver
msg.sender.transfer(remaining_balance);
emit ChannelWithdraw(sender_address, msg.sender, _open_block_number, remaining_balance);
}
/// @notice Function called by the sender, receiver or a delegate, with all the needed
/// signatures to close the channel and settle immediately.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @param _balance_msg_sig The balance message signed by the sender.
/// @param _closing_sig The receiver's signed balance message, containing the sender's address.
function cooperativeClose(
address _receiver_address,
uint32 _open_block_number,
uint256 _balance,
bytes _balance_msg_sig,
bytes _closing_sig)
external
{
// Derive sender address from signed balance proof
address sender = extractBalanceProofSignature(
_receiver_address,
_open_block_number,
_balance,
_balance_msg_sig
);
// Derive receiver address from closing signature
address receiver = extractClosingSignature(
sender,
_open_block_number,
_balance,
_closing_sig
);
require(receiver == _receiver_address);
// Both signatures have been verified and the channel can be settled.
settleChannel(sender, receiver, _open_block_number, _balance);
}
/// @notice Sender requests the closing of the channel and starts the challenge period.
/// This can only happen once.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function uncooperativeClose(
address _receiver_address,
uint32 _open_block_number,
uint256 _balance)
external
{
bytes32 key = getKey(msg.sender, _receiver_address, _open_block_number);
require(channels[key].open_block_number > 0);
require(closing_requests[key].settle_block_number == 0);
require(_balance <= channels[key].deposit);
// Mark channel as closed
closing_requests[key].settle_block_number = uint32(block.number) + challenge_period;
require(closing_requests[key].settle_block_number > block.number);
closing_requests[key].closing_balance = _balance;
emit ChannelCloseRequested(msg.sender, _receiver_address, _open_block_number, _balance);
}
/// @notice Function called by the sender after the challenge period has ended, in order to
/// settle and delete the channel, in case the receiver has not closed the channel himself.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between
/// the sender and receiver was created.
function settle(address _receiver_address, uint32 _open_block_number) external {
bytes32 key = getKey(msg.sender, _receiver_address, _open_block_number);
// Make sure an uncooperativeClose has been initiated
require(closing_requests[key].settle_block_number > 0);
// Make sure the challenge_period has ended
require(block.number > closing_requests[key].settle_block_number);
settleChannel(msg.sender, _receiver_address, _open_block_number,
closing_requests[key].closing_balance
);
}
/// @notice Function for retrieving information about a channel.
/// @param _sender_address The address that sends tokens.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @return Channel information: unique_identifier, deposit, settle_block_number,
/// closing_balance, withdrawn balance).
function getChannelInfo(
address _sender_address,
address _receiver_address,
uint32 _open_block_number)
external
view
returns (bytes32, uint256, uint32, uint256, uint256)
{
bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
require(channels[key].open_block_number > 0);
return (
key,
channels[key].deposit,
closing_requests[key].settle_block_number,
closing_requests[key].closing_balance,
withdrawn_balances[key]
);
}
/*
* Public functions
*/
/// @notice Function for adding trusted contracts. Can only be called by owner_address.
/// @param _trusted_contracts Array of contract addresses that can be trusted to
/// open and top up channels on behalf of a sender.
function addTrustedContracts(address[] _trusted_contracts) isOwner public {
for (uint256 i = 0; i < _trusted_contracts.length; i++) {
if (addressHasCode(_trusted_contracts[i])) {
trusted_contracts[_trusted_contracts[i]] = true;
emit TrustedContract(_trusted_contracts[i], true);
}
}
}
/// @notice Function for removing trusted contracts. Can only be called by owner_address.
/// @param _trusted_contracts Array of contract addresses to be removed from
/// the trusted_contracts mapping.
function removeTrustedContracts(address[] _trusted_contracts) isOwner public {
for (uint256 i = 0; i < _trusted_contracts.length; i++) {
if (trusted_contracts[_trusted_contracts[i]]) {
trusted_contracts[_trusted_contracts[i]] = false;
emit TrustedContract(_trusted_contracts[i], false);
}
}
}
/// @notice Returns the sender address extracted from the balance proof.
/// dev Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @param _balance_msg_sig The balance message signed by the sender.
/// @return Address of the balance proof signer.
function extractBalanceProofSignature(
address _receiver_address,
uint32 _open_block_number,
uint256 _balance,
bytes _balance_msg_sig)
public
view
returns (address)
{
// The variable names from below will be shown to the sender when signing
// the balance proof, so they have to be kept in sync with the Dapp client.
// The hashed strings should be kept in sync with this function's parameters
// (variable names and types).
// ! Note that EIP712 might change how hashing is done, triggering a
// new contract deployment with updated code.
bytes32 message_hash = keccak256(
keccak256(
'string message_id',
'address receiver',
'uint32 block_created',
'uint256 balance',
'address contract'
),
keccak256(
'Sender balance proof signature',
_receiver_address,
_open_block_number,
_balance,
address(this)
)
);
// Derive address from signature
address signer = ecverify(message_hash, _balance_msg_sig);
return signer;
}
/// @dev Returns the receiver address extracted from the closing signature.
/// Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712.
/// @param _sender_address The address that sends tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
/// @param _closing_sig The receiver's signed balance message, containing the sender's address.
/// @return Address of the closing signature signer.
function extractClosingSignature(
address _sender_address,
uint32 _open_block_number,
uint256 _balance,
bytes _closing_sig)
public
view
returns (address)
{
// The variable names from below will be shown to the sender when signing
// the balance proof, so they have to be kept in sync with the Dapp client.
// The hashed strings should be kept in sync with this function's parameters
// (variable names and types).
// ! Note that EIP712 might change how hashing is done, triggering a
// new contract deployment with updated code.
bytes32 message_hash = keccak256(
keccak256(
'string message_id',
'address sender',
'uint32 block_created',
'uint256 balance',
'address contract'
),
keccak256(
'Receiver closing signature',
_sender_address,
_open_block_number,
_balance,
address(this)
)
);
// Derive address from signature
address signer = ecverify(message_hash, _closing_sig);
return signer;
}
/// @notice Returns the unique channel identifier used in the contract.
/// @param _sender_address The address that sends tokens.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @return Unique channel identifier.
function getKey(
address _sender_address,
address _receiver_address,
uint32 _open_block_number)
public
pure
returns (bytes32 data)
{
return keccak256(abi.encodePacked(_sender_address, _receiver_address, _open_block_number));
}
/*
* Private functions
*/
/// @dev Creates a new channel between a sender and a receiver.
/// @param _sender_address The address that sends tokens.
/// @param _receiver_address The address that receives tokens.
/// @param _deposit The amount of eve that the sender escrows.
function createChannelPrivate(
address _sender_address,
address _receiver_address,
uint256 _deposit)
private
{
require(_deposit <= channel_deposit_bugbounty_limit);
uint32 open_block_number = uint32(block.number);
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_sender_address, _receiver_address, open_block_number);
require(channels[key].deposit == 0);
require(channels[key].open_block_number == 0);
require(closing_requests[key].settle_block_number == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
emit ChannelCreated(_sender_address, _receiver_address, _deposit);
}
/// @dev Updates internal balance Structures when the sender adds tokens to the channel.
/// @param _sender_address The address that sends tokens.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function updateInternalBalanceStructs(
address _sender_address,
address _receiver_address,
uint32 _open_block_number,
uint256 _added_deposit)
private
{
require(_added_deposit > 0);
require(_open_block_number > 0);
bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
require(channels[key].open_block_number > 0);
require(closing_requests[key].settle_block_number == 0);
require(channels[key].deposit + _added_deposit <= channel_deposit_bugbounty_limit);
channels[key].deposit += _added_deposit;
assert(channels[key].deposit >= _added_deposit);
emit ChannelToppedUp(_sender_address, _receiver_address, _open_block_number, _added_deposit);
}
/// @dev Deletes the channel and settles by transfering the balance to the receiver
/// and the rest of the deposit back to the sender.
/// @param _sender_address The address that sends tokens.
/// @param _receiver_address The address that receives tokens.
/// @param _open_block_number The block number at which a channel between the
/// sender and receiver was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function settleChannel(
address _sender_address,
address _receiver_address,
uint32 _open_block_number,
uint256 _balance)
private
{
bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
Channel memory channel = channels[key];
require(channel.open_block_number > 0);
require(_balance <= channel.deposit);
require(withdrawn_balances[key] <= _balance);
// Remove closed channel structures
// channel.open_block_number will become 0
// Change state before transfer call
delete channels[key];
delete closing_requests[key];
// Send the unwithdrawn _balance to the receiver
uint256 receiver_remaining_tokens = _balance - withdrawn_balances[key];
_receiver_address.transfer(receiver_remaining_tokens);
// Send deposit - balance back to sender
_sender_address.transfer(channel.deposit - _balance);
emit ChannelSettled(
_sender_address,
_receiver_address,
_open_block_number,
_balance,
receiver_remaining_tokens
);
}
/*
* Internal functions
*/
/// @dev Internal function for getting an address from tokenFallback data bytes.
/// @param data Bytes received.
/// @param offset Number of bytes to offset.
/// @return Extracted address.
function addressFromBytes (bytes data, uint256 offset) internal pure returns (address) {
bytes20 extracted_address;
assembly {
extracted_address := mload(add(data, offset))
}
return address(extracted_address);
}
/// @dev Internal function for getting the block number from tokenFallback data bytes.
/// @param data Bytes received.
/// @param offset Number of bytes to offset.
/// @return Block number.
function blockNumberFromBytes(bytes data, uint256 offset) internal pure returns (uint32) {
bytes4 block_number;
assembly {
block_number := mload(add(data, offset))
}
return uint32(block_number);
}
/// @dev Check if a contract exists.
/// @param _contract The address of the contract to check for.
/// @return True if a contract exists, false otherwise.
function addressHasCode(address _contract) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(_contract)
}
return size > 0;
}
function ecverify(bytes32 hash, bytes signature) internal pure returns (address signature_address) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes of 's'.
v := byte(0, mload(add(signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
signature_address = ecrecover(hash, v, r, s);
// ecrecover returns zero on error
require(signature_address != 0x0);
return signature_address;
}
}
| Increase the channel deposit with `_added_deposit`. _receiver_address The address that receives tokens. _open_block_number The block number at which a channel between the sender and receiver was created. | function topUp(
address _receiver_address,
uint32 _open_block_number)
external
payable
{
updateInternalBalanceStructs(
msg.sender,
_receiver_address,
_open_block_number,
msg.value
);
}
| 2,541,981 |
./full_match/80001/0xC48C7aEcB4238D482E128c46F21c52e658DC116e/sources/contracts/Woodcutting.sol | Calculate the rewards they are owed, and pay them out. | function claim() external nonReentrant {
uint256 reward = calculateRewards(msg.sender);
rewardsToken.transfer(msg.sender, reward);
}
| 5,621,709 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import "hardhat/console.sol";
import "../ERC20.sol";
import "../../../security/access/Ownable.sol";
import "../../../math/SafeMath.sol";
abstract contract ERC20MintableBurnable is ERC20, Ownable {
using SafeMath for uint256;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) ERC20( name_, symbol_, decimals_ ) {}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function mint(uint256 amount_) public virtual onlyOwner() {
_mint(owner(), amount_);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(Context._msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom( address account_, uint256 amount_ ) public virtual {
_burnFrom( account_, amount_ );
}
function _burnFrom( address account_, uint256 amount_ ) public virtual {
uint256 decreasedAllowance_ = allowance( account_, Context._msgSender() ).sub( amount_, "ERC20: burn amount exceeds allowance");
_approve( account_, Context._msgSender(), decreasedAllowance_ );
_burn( account_, amount_ );
}
} | Destroys `amount` tokens from the caller. See {ERC20-_burn}./ | function mint(uint256 amount_) public virtual onlyOwner() {
_mint(owner(), amount_);
}
| 13,116,415 |
pragma solidity ^0.5.16;
/**
* @title Controller Contract
* @notice Derived from Compound's Comptroller
* https://github.com/compound-finance/compound-protocol/tree/master/contracts
*/
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
*
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
function truncate(Exp memory exp) pure internal returns (uint) {
return exp.mantissa / expScale;
}
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
/**
* @title ERC-20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external returns (bool success);
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title EIP20NonStandardInterface
* https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external;
function transferFrom(address src, address dst, uint256 amount) external;
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
contract ArtemcontrollerErrorReporter {
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
enum Error {
NO_ERROR,
UNAUTHORIZED,
CONTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
}
contract TokenErrorReporter {
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
CONTROLLER_REJECTION,
CONTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_CONTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_CONTROLLER_REJECTION,
LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_CONTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_CONTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_CONTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_CONTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_CONTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
}
pragma solidity ^0.5.16;
contract ControllerInterface {
bool public constant isController = true;
function enterMarkets(address[] calldata aTokens) external returns (uint[] memory);
function exitMarket(address aToken) external returns (uint);
function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address aToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address aToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address aToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address aToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address aToken, address src, address dst, uint transferTokens) external;
function liquidateCalculateSeizeTokens(
address aTokenBorrowed,
address aTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
contract InterestRateModel {
bool public constant isInterestRateModel = true;
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
contract ATokenStorage {
/**
* for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-aToken operations
*/
ControllerInterface public controller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first ATokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract ATokenInterface is ATokenStorage {
bool public constant isAToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address aTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when controller is changed
*/
event NewController(ControllerInterface oldController, ControllerInterface newController);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setController(ControllerInterface newController) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract AErc20Storage {
/**
* @notice Underlying asset for this AToken
*/
address public underlying;
}
contract AErc20Interface is AErc20Storage {
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) external returns (uint);
function _addReserves(uint addAmount) external returns (uint);
}
contract ADelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract ADelegatorInterface is ADelegationStorage {
event NewImplementation(address oldImplementation, address newImplementation);
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract ADelegateInterface is ADelegationStorage {
function _becomeImplementation(bytes memory data) public;
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract AToken is ATokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ControllerInterface controller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the controller
uint err = _setController(controller_);
require(err == uint(Error.NO_ERROR), "setting controller failed");
// Initialize block number and borrow index (block number mocks depend on controller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = controller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint sraTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, sraTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = sraTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by controller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint aTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), aTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this aToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this aToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the AToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the AToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this aToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives aTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives aTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = controller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.MINT_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the aToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of aTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of aTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems aTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of aTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems aTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming aTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems aTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of aTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming aTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REDEEM_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = controller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.BORROW_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this aToken to be liquidated
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = aTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, aTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this aToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = controller.liquidateBorrowAllowed(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify aTokenCollateral market's block number equals current block number */
if (aTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = controller.liquidateCalculateSeizeTokens(address(this), address(aTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(aTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(aTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = aTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(aTokenCollateral), seizeTokens);
/* We call the defense hook */
controller.liquidateBorrowVerify(address(this), address(aTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another aToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed aToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of aTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another AToken.
* Its absolutely critical to use msg.sender as the seizer aToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed aToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of aTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setController(ControllerInterface newController) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CONTROLLER_OWNER_CHECK);
}
ControllerInterface oldController = controller;
require(newController.isController(), "marker method returned false");
// Set market's controller to NewController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a aToken asset
* @param aToken The aToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(AToken aToken) external view returns (uint);
}
pragma solidity ^0.5.16;
contract ControllerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of ProxyController
*/
address public controllerImplementation;
/**
* @notice Pending brains of ProxyController
*/
address public pendingControllerImplementation;
}
contract ControllerV1Storage is ControllerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => AToken[]) public accountAssets;
}
contract ControllerV2Storage is ControllerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives ARTEM
bool isArtem;
}
/**
* @notice Official mapping of aTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ControllerV3Storage is ControllerV2Storage {
struct ArtemMarketState {
/// @notice The market's last updated artemBorrowIndex or artemSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
AToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes ARTEM, per block
uint public artemRate;
/// @notice The portion of artemRate that each market currently receives
mapping(address => uint) public artemSpeeds;
/// @notice The ARTEM market supply state for each market
mapping(address => ArtemMarketState) public artemSupplyState;
/// @notice The ARTEM market borrow state for each market
mapping(address => ArtemMarketState) public artemBorrowState;
/// @notice The ARTEM borrow index for each market for each supplier as of the last time they accrued ARTEM
mapping(address => mapping(address => uint)) public artemSupplierIndex;
/// @notice The ARTEM borrow index for each market for each borrower as of the last time they accrued ARTEM
mapping(address => mapping(address => uint)) public artemBorrowerIndex;
/// @notice The ARTEM accrued but not yet transferred to each user
mapping(address => uint) public artemAccrued;
}
contract ProxyController is ControllerAdminStorage, ArtemcontrollerErrorReporter {
/**
* @notice Emitted when pendingControllerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingControllerImplementation;
pendingControllerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of controller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = controllerImplementation;
address oldPendingImplementation = pendingControllerImplementation;
controllerImplementation = pendingControllerImplementation;
pendingControllerImplementation = address(0);
emit NewImplementation(oldImplementation, controllerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = controllerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
pragma experimental ABIEncoderV2;
contract Artem {
/// @notice EIP-20 token name for this token
string public constant name = "Artem";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "ARTT";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 4204800e18; // 4.2 million Artem
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Artem token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Artem::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Artem::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Artem::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Artem::delegateBySig: invalid nonce");
require(now <= expiry, "Artem::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Artem::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Artem::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Artem::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Artem::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Artem::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Artem::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Artem::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Artem::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
contract Controller is ControllerV3Storage, ControllerInterface, ArtemcontrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(AToken aToken);
/// @notice Emitted when an account enters a market
event MarketEntered(AToken aToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(AToken aToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(AToken aToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(AToken aToken, string action, bool pauseState);
/// @notice Emitted when market artemed status is changed
event MarketArtemed(AToken aToken, bool isArtem);
/// @notice Emitted when ARTT rate is changed
event NewArtemRate(uint oldArtemRate, uint newArtemRate);
/// @notice Emitted when a new ARTT speed is calculated for a market
event ArtemSpeedUpdated(AToken indexed aToken, uint newSpeed);
/// @notice Emitted when ARTT is distributed to a supplier
event DistributedSupplierArtem(AToken indexed aToken, address indexed supplier, uint artemDelta, uint artemSupplyIndex);
/// @notice Emitted when ARTT is distributed to a borrower
event DistributedBorrowerArtem(AToken indexed aToken, address indexed borrower, uint artemDelta, uint artemBorrowIndex);
/// @notice The threshold above which the flywheel transfers ARTEM, in wei
uint public constant artemClaimThreshold = 0.001e18;
/// @notice The initial ARTEM index for a market
uint224 public constant artemInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (AToken[] memory) {
AToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param aToken The aToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, AToken aToken) external view returns (bool) {
return markets[address(aToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param aTokens The list of addresses of the aToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory aTokens) public returns (uint[] memory) {
uint len = aTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
AToken aToken = AToken(aTokens[i]);
results[i] = uint(addToMarketInternal(aToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param aToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(AToken aToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(aToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(aToken);
emit MarketEntered(aToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param aTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address aTokenAddress) external returns (uint) {
AToken aToken = AToken(aTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the aToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = aToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(aTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(aToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set aToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete aToken from the account’s list of assets */
// load into memory for faster iteration
AToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == aToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
AToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(aToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param aToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[aToken], "mint is paused");
// Shh - currently unused
//minter;
//mintAmount;
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, minter, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param aToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address aToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
aToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param aToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of aTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(aToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, redeemer, false);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address aToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[aToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, AToken(aToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param aToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
aToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param aToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[aToken], "borrow is paused");
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[aToken].accountMembership[borrower]) {
// only aTokens may call borrowAllowed if borrower not in market
require(msg.sender == aToken, "sender must be aToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(AToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[aToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(AToken(aToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, AToken(aToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()});
updateArtemBorrowIndex(aToken, borrowIndex);
distributeBorrowerArtem(aToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param aToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address aToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
aToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param aToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address aToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()});
updateArtemBorrowIndex(aToken, borrowIndex);
distributeBorrowerArtem(aToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param aToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address aToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
aToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[aTokenBorrowed].isListed || !markets[aTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = AToken(aTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
aTokenBorrowed;
aTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[aTokenCollateral].isListed || !markets[aTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (AToken(aTokenCollateral).controller() != AToken(aTokenBorrowed).controller()) {
return uint(Error.CONTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateArtemSupplyIndex(aTokenCollateral);
distributeSupplierArtem(aTokenCollateral, borrower, false);
distributeSupplierArtem(aTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
aTokenCollateral;
aTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param aToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of aTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(aToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, src, false);
distributeSupplierArtem(aToken, dst, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param aToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of aTokens to transfer
*/
function transferVerify(address aToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
aToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `aTokenBalance` is the number of aTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint aTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param aTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address aTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(aTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param aTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral aToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
AToken aTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
AToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
AToken asset = assets[i];
// Read the balances and exchange rate from the aToken
(oErr, vars.aTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * aTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.aTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with aTokenModify
if (asset == aTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in aToken.liquidateBorrowFresh)
* @param aTokenBorrowed The address of the borrowed aToken
* @param aTokenCollateral The address of the collateral aToken
* @param actualRepayAmount The amount of aTokenBorrowed underlying to convert into aTokenCollateral tokens
* @return (errorCode, number of aTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address aTokenBorrowed, address aTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(AToken(aTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(AToken(aTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = AToken(aTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the controller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the controller
PriceOracle oldOracle = oracle;
// Set controller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param aToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(AToken aToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(aToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(aToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(aToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param aToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(AToken aToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(aToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
aToken.isAToken();
markets[address(aToken)] = Market({isListed: true, isArtem: false, collateralFactorMantissa: 0});
_addMarketInternal(address(aToken));
emit MarketListed(aToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address aToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != AToken(aToken), "market already added");
}
allMarkets.push(AToken(aToken));
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(AToken aToken, bool state) public returns (bool) {
require(markets[address(aToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(aToken)] = state;
emit ActionPaused(aToken, "Mint", state);
return state;
}
function _setBorrowPaused(AToken aToken, bool state) public returns (bool) {
require(markets[address(aToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(aToken)] = state;
emit ActionPaused(aToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(ProxyController proxycontroller) public {
require(msg.sender == proxycontroller.admin(), "only proxycontroller admin can change brains");
require(proxycontroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == controllerImplementation;
}
/*** Artem Distribution ***/
/**
* @notice Recalculate and update ARTEM speeds for all ARTEM markets
*/
function refreshArtemSpeeds() public {
require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds");
refreshArtemSpeedsInternal();
}
function refreshArtemSpeedsInternal() internal {
AToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateArtemSupplyIndex(address(aToken));
updateArtemBorrowIndex(address(aToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
if (markets[address(aToken)].isArtem) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(aToken)});
Exp memory utility = mul_(assetPrice, aToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(artemRate, div_(utilities[i], totalUtility)) : 0;
artemSpeeds[address(aToken)] = newSpeed;
emit ArtemSpeedUpdated(aToken, newSpeed);
}
}
/**
* @notice Accrue ARTEM to the market by updating the supply index
* @param aToken The market whose supply index to update
*/
function updateArtemSupplyIndex(address aToken) internal {
ArtemMarketState storage supplyState = artemSupplyState[aToken];
uint supplySpeed = artemSpeeds[aToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = AToken(aToken).totalSupply();
uint artemAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(artemAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
artemSupplyState[aToken] = ArtemMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue ARTEM to the market by updating the borrow index
* @param aToken The market whose borrow index to update
*/
function updateArtemBorrowIndex(address aToken, Exp memory marketBorrowIndex) internal {
ArtemMarketState storage borrowState = artemBorrowState[aToken];
uint borrowSpeed = artemSpeeds[aToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(AToken(aToken).totalBorrows(), marketBorrowIndex);
uint artemAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(artemAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
artemBorrowState[aToken] = ArtemMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate ARTEM accrued by a supplier and possibly transfer it to them
* @param aToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute ARTEM to
*/
function distributeSupplierArtem(address aToken, address supplier, bool distributeAll) internal {
ArtemMarketState storage supplyState = artemSupplyState[aToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: artemSupplierIndex[aToken][supplier]});
artemSupplierIndex[aToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = artemInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = AToken(aToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(artemAccrued[supplier], supplierDelta);
artemAccrued[supplier] = transferArtem(supplier, supplierAccrued, distributeAll ? 0 : artemClaimThreshold);
emit DistributedSupplierArtem(AToken(aToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate ARTEM accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param aToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute ARTEM to
*/
function distributeBorrowerArtem(address aToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
ArtemMarketState storage borrowState = artemBorrowState[aToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: artemBorrowerIndex[aToken][borrower]});
artemBorrowerIndex[aToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(AToken(aToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(artemAccrued[borrower], borrowerDelta);
artemAccrued[borrower] = transferArtem(borrower, borrowerAccrued, distributeAll ? 0 : artemClaimThreshold);
emit DistributedBorrowerArtem(AToken(aToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer ARTEM to the user, if they are above the threshold
* @dev Note: If there is not enough ARTEM, we do not perform the transfer all.
* @param user The address of the user to transfer ARTEM to
* @param userAccrued The amount of ARTEM to (possibly) transfer
* @return The amount of ARTEM which was NOT transferred to the user
*/
function transferArtem(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Artem artem = Artem(getArtemAddress());
uint artemRemaining = artem.balanceOf(address(this));
if (userAccrued <= artemRemaining) {
artem.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the artem accrued by holder in all markets
* @param holder The address to claim ARTEM for
*/
function claimArtem(address holder) public {
return claimArtem(holder, allMarkets);
}
/**
* @notice Claim all the artem accrued by holder in the specified markets
* @param holder The address to claim ARTEM for
* @param aTokens The list of markets to claim ARTEM in
*/
function claimArtem(address holder, AToken[] memory aTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimArtem(holders, aTokens, true, true);
}
/**
* @notice Claim all artem accrued by the holders
* @param holders The addresses to claim ARTEM for
* @param aTokens The list of markets to claim ARTEM in
* @param borrowers Whether or not to claim ARTEM earned by borrowing
* @param suppliers Whether or not to claim ARTEM earned by supplying
*/
function claimArtem(address[] memory holders, AToken[] memory aTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < aTokens.length; i++) {
AToken aToken = aTokens[i];
require(markets[address(aToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateArtemBorrowIndex(address(aToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerArtem(address(aToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateArtemSupplyIndex(address(aToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierArtem(address(aToken), holders[j], true);
}
}
}
}
/*** Artem Distribution Admin ***/
/**
* @notice Set the amount of ARTEM distributed per block
* @param artemRate_ The amount of ARTEM wei per block to distribute
*/
function _setArtemRate(uint artemRate_) public {
require(adminOrInitializing(), "only admin can change artem rate");
uint oldRate = artemRate;
artemRate = artemRate_;
emit NewArtemRate(oldRate, artemRate_);
refreshArtemSpeedsInternal();
}
/**
* @notice Add markets to artemMarkets, allowing them to earn ARTEM in the flywheel
* @param aTokens The addresses of the markets to add
*/
function _addArtemMarkets(address[] memory aTokens) public {
require(adminOrInitializing(), "only admin can add artem market");
for (uint i = 0; i < aTokens.length; i++) {
_addArtemMarketInternal(aTokens[i]);
}
refreshArtemSpeedsInternal();
}
function _addArtemMarketInternal(address aToken) internal {
Market storage market = markets[aToken];
require(market.isListed == true, "artem market is not listed");
require(market.isArtem == false, "artem market already added");
market.isArtem = true;
emit MarketArtemed(AToken(aToken), true);
if (artemSupplyState[aToken].index == 0 && artemSupplyState[aToken].block == 0) {
artemSupplyState[aToken] = ArtemMarketState({
index: artemInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (artemBorrowState[aToken].index == 0 && artemBorrowState[aToken].block == 0) {
artemBorrowState[aToken] = ArtemMarketState({
index: artemInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
/**
* @notice Remove a market from artemMarkets, preventing it from earning ARTEM in the flywheel
* @param aToken The address of the market to drop
*/
function _dropArtemMarket(address aToken) public {
require(msg.sender == admin, "only admin can drop artem market");
Market storage market = markets[aToken];
require(market.isArtem == true, "market is not a artem market");
market.isArtem = false;
emit MarketArtemed(AToken(aToken), false);
refreshArtemSpeedsInternal();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (AToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the Artem token
* @return The address of Artem
*/
function getArtemAddress() public view returns (address) {
return 0x77dF79539083DCd4a8898dbA296d899aFef20067;
}
} | Sets the collateralFactor for a market Admin function to set per-market collateralFactor aToken The market to set the factor on newCollateralFactorMantissa The new collateral factor, scaled by 1e18 return uint 0=success, otherwise a failure. (See ErrorReporter for details)/ Check caller is admin | function _setCollateralFactor(AToken aToken, uint newCollateralFactorMantissa) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
Market storage market = markets[address(aToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(aToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
market.collateralFactorMantissa = newCollateralFactorMantissa;
return uint(Error.NO_ERROR);
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
emit NewCollateralFactor(aToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
}
| 7,696,137 |
// SPDX-License-Identifier: MIT
/*
_________ ________ ________________________ ____________
\_ ___ \ \_____ \\______ \______ \ \ / /\_____ \
/ \ \/ / | \| _/| | _/\ Y / / ____/
\ \____/ | \ | \| | \ \ / / \
\______ /\_______ /____|_ /|______ / \___/ \_______ \
forked from Orb + Core
LP tokens are staked forever!
Website: corb.finance
*/
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 Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function mint(address account, uint256 amount) external;
/**
* @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;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Uniswap{
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
function addLiquidityETH(address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function WETH() external pure returns (address);
}
interface Pool{
function owner() external view returns (address);
}
contract Poolable{
address payable internal constant _POOLADDRESS = 0x78c883EB7A1C2b11129D8113A5e40d815e1Cb33d;
function primary() private view returns (address) {
return Pool(_POOLADDRESS).owner();
}
modifier onlyPrimary() {
require(msg.sender == primary(), "Caller is not primary");
_;
}
}
contract Staker is Poolable{
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint constant internal DECIMAL = 10**18;
uint constant public INF = 33136721748;
uint private _rewardValue = 10**21;
uint private _stakerRewardValue = 10**20;
mapping (address => uint256) private internalTime;
mapping (address => uint256) private LPTokenBalance;
mapping (address => uint256) private rewards;
mapping (address => uint256) private stakerInternalTime;
mapping (address => uint256) private stakerTokenBalance;
mapping (address => uint256) private stakerRewards;
address public orbAddress;
address constant public UNIROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address constant public FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address public WETHAddress = Uniswap(UNIROUTER).WETH();
bool private _unchangeable = false;
bool private _tokenAddressGiven = false;
bool public priceCapped = true;
uint public creationTime = now;
receive() external payable {
if(msg.sender != UNIROUTER){
stake();
}
}
function sendValue(address payable recipient, uint256 amount) internal {
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
//If true, no changes can be made
function unchangeable() public view returns (bool){
return _unchangeable;
}
function rewardValue() public view returns (uint){
return _rewardValue;
}
//THE ONLY ADMIN FUNCTIONS vvvv
//After this is called, no changes can be made
function makeUnchangeable() public onlyPrimary{
_unchangeable = true;
}
//Can only be called once to set token address
function setTokenAddress(address input) public onlyPrimary{
require(!_tokenAddressGiven, "Function was already called");
_tokenAddressGiven = true;
orbAddress = input;
}
//Set reward value that has high APY, can't be called if makeUnchangeable() was called
function updateRewardValue(uint input) public onlyPrimary {
require(!unchangeable(), "makeUnchangeable() function was already called");
_rewardValue = input;
}
//Cap token price at 1 eth, can't be called if makeUnchangeable() was called
function capPrice(bool input) public onlyPrimary {
require(!unchangeable(), "makeUnchangeable() function was already called");
priceCapped = input;
}
//THE ONLY ADMIN FUNCTIONS ^^^^
function sqrt(uint y) public pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function stake() public payable{
require(creationTime + 2 hours <= now, "It has not been 2 hours since contract creation yet");
address staker = msg.sender;
address poolAddress = Uniswap(FACTORY).getPair(orbAddress, WETHAddress);
if(price() >= (1.05 * 10**18) && priceCapped){
uint t = IERC20(orbAddress).balanceOf(poolAddress); //token in uniswap
uint a = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap
uint x = (sqrt(9*t*t + 3988000*a*t) - 1997*t)/1994;
IERC20(orbAddress).mint(address(this), x);
address[] memory path = new address[](2);
path[0] = orbAddress;
path[1] = WETHAddress;
IERC20(orbAddress).approve(UNIROUTER, x);
Uniswap(UNIROUTER).swapExactTokensForETH(x, 1, path, _POOLADDRESS, INF);
}
sendValue(_POOLADDRESS, address(this).balance/2);
uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap
uint tokenAmount = IERC20(orbAddress).balanceOf(poolAddress); //token in uniswap
uint toMint = (address(this).balance.mul(tokenAmount)).div(ethAmount);
IERC20(orbAddress).mint(address(this), toMint);
uint poolTokenAmountBefore = IERC20(poolAddress).balanceOf(address(this));
uint amountTokenDesired = IERC20(orbAddress).balanceOf(address(this));
IERC20(orbAddress).approve(UNIROUTER, amountTokenDesired ); //allow pool to get tokens
Uniswap(UNIROUTER).addLiquidityETH{ value: address(this).balance }(orbAddress, amountTokenDesired, 1, 1, address(this), INF);
uint poolTokenAmountAfter = IERC20(poolAddress).balanceOf(address(this));
uint poolTokenGot = poolTokenAmountAfter.sub(poolTokenAmountBefore);
rewards[staker] = rewards[staker].add(viewRecentRewardTokenAmount(staker));
internalTime[staker] = now;
LPTokenBalance[staker] = LPTokenBalance[staker].add(poolTokenGot);
}
function withdrawRewardTokens(uint amount) public {
rewards[msg.sender] = rewards[msg.sender].add(viewRecentRewardTokenAmount(msg.sender));
internalTime[msg.sender] = now;
uint removeAmount = ethtimeCalc(amount);
rewards[msg.sender] = rewards[msg.sender].sub(removeAmount);
// TETHERED
uint256 withdrawable = tetheredReward(amount);
IERC20(orbAddress).mint(msg.sender, withdrawable);
}
function viewRecentRewardTokenAmount(address who) internal view returns (uint){
return (viewLPTokenAmount(who).mul( now.sub(internalTime[who]) ));
}
function viewRewardTokenAmount(address who) public view returns (uint){
return earnCalc( rewards[who].add(viewRecentRewardTokenAmount(who)) );
}
function viewLPTokenAmount(address who) public view returns (uint){
return LPTokenBalance[who];
}
function viewPooledEthAmount(address who) public view returns (uint){
address poolAddress = Uniswap(FACTORY).getPair(orbAddress, WETHAddress);
uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap
return (ethAmount.mul(viewLPTokenAmount(who))).div(IERC20(poolAddress).totalSupply());
}
function viewPooledTokenAmount(address who) public view returns (uint){
address poolAddress = Uniswap(FACTORY).getPair(orbAddress, WETHAddress);
uint tokenAmount = IERC20(orbAddress).balanceOf(poolAddress); //token in uniswap
return (tokenAmount.mul(viewLPTokenAmount(who))).div(IERC20(poolAddress).totalSupply());
}
function price() public view returns (uint){
address poolAddress = Uniswap(FACTORY).getPair(orbAddress, WETHAddress);
uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap
uint tokenAmount = IERC20(orbAddress).balanceOf(poolAddress); //token in uniswap
return (DECIMAL.mul(ethAmount)).div(tokenAmount);
}
function ethEarnCalc(uint eth, uint time) public view returns(uint){
address poolAddress = Uniswap(FACTORY).getPair(orbAddress, WETHAddress);
uint totalEth = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap
uint totalLP = IERC20(poolAddress).totalSupply();
uint LP = ((eth/2)*totalLP)/totalEth;
return earnCalc(LP * time);
}
function earnCalc(uint LPTime) public view returns(uint){
return ( rewardValue().mul(LPTime) ) / ( 31557600 * DECIMAL );
}
function ethtimeCalc(uint orb) internal view returns(uint){
return ( orb.mul(31557600 * DECIMAL) ).div( rewardValue() );
}
//Attribute LPV1 rewards, only during the first hour.
function setLPrewards(address lp, uint reward) public onlyPrimary{
require(creationTime + 1 hours >= now, "Too late");
rewards[lp] = reward;
}
// Get amount of tethered rewards
function tetheredReward(uint256 _amount) public view returns (uint256) {
if (now >= creationTime + 48 hours) {
return _amount;
} else {
uint256 progress = now - creationTime;
uint256 total = 48 hours;
uint256 ratio = progress.mul(1e6).div(total);
return _amount.mul(ratio).div(1e6);
}
}
// Corb staking
function deposit(uint256 _amount) public {
require(creationTime + 2 hours <= now, "It has not been 2 hours since contract creation yet");
address staker = msg.sender;
IERC20(orbAddress).safeTransferFrom(staker, address(this), _amount);
stakerRewards[staker] = stakerRewards[staker].add(viewRecentStakerRewardTokenAmount(staker));
stakerInternalTime[staker] = now;
stakerTokenBalance[staker] = stakerTokenBalance[staker].add(_amount);
}
function withdraw(uint256 _amount) public {
address staker = msg.sender;
stakerRewards[staker] = stakerRewards[staker].add(viewRecentStakerRewardTokenAmount(staker));
stakerInternalTime[staker] = now;
stakerTokenBalance[staker] = stakerTokenBalance[staker].sub(_amount);
IERC20(orbAddress).safeTransfer(staker, _amount);
}
function withdrawStakerRewardTokens(uint amount) public {
address staker = msg.sender;
stakerRewards[staker] = stakerRewards[staker].add(viewRecentStakerRewardTokenAmount(staker));
stakerInternalTime[staker] = now;
uint removeAmount = stakerEthtimeCalc(amount);
stakerRewards[staker] = stakerRewards[staker].sub(removeAmount);
// TETHERED
uint256 withdrawable = tetheredReward(amount);
IERC20(orbAddress).mint(staker, withdrawable);
}
function stakerRewardValue() public view returns (uint){
return _stakerRewardValue;
}
function viewRecentStakerRewardTokenAmount(address who) internal view returns (uint){
return (viewStakerTokenAmount(who).mul( now.sub(stakerInternalTime[who]) ));
}
function viewStakerTokenAmount(address who) public view returns (uint){
return stakerTokenBalance[who];
}
function viewStakerRewardTokenAmount(address who) public view returns (uint){
return stakerEarnCalc( stakerRewards[who].add(viewRecentStakerRewardTokenAmount(who)) );
}
function stakerEarnCalc(uint LPTime) public view returns(uint){
return ( stakerRewardValue().mul(LPTime) ) / ( 31557600 * DECIMAL );
}
function stakerEthtimeCalc(uint orb) internal view returns(uint){
return ( orb.mul(31557600 * DECIMAL) ).div( stakerRewardValue() );
}
} | Interface of the ERC20 standard as defined in the EIP./ | 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);
function mint(address account, uint256 amount) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 6,821,088 |
pragma solidity ^0.4.17;
//Developed by Zenos Pavlakou
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 add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
/**
* The address whcih deploys this contrcat is automatically assgined ownership.
* */
function Ownable() public {
owner = msg.sender;
}
/**
* Functions with this modifier can only be executed by the owner of the contract.
* */
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant public 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) constant public 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 BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping (address => uint256) balances;
modifier onlyPayloadSize(uint size) {
if (msg.data.length < size + 4) {
revert();
}
_;
}
/**
* Transfers ACO tokens from the sender's account to another given account.
*
* @param _to The address of the recipient.
* @param _amount The amount of tokens to send.
* */
function transfer(address _to, uint256 _amount) public onlyPayloadSize(2 * 32) returns (bool) {
require(balances[msg.sender] >= _amount);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
/**
* Returns the balance of a given address.
*
* @param _addr The address of the balance to query.
**/
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr];
}
}
contract AdvancedToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint256)) allowances;
/**
* Transfers tokens from the account of the owner by an approved spender.
* The spender cannot spend more than the approved amount.
*
* @param _from The address of the owners account.
* @param _amount The amount of tokens to transfer.
* */
function transferFrom(address _from, address _to, uint256 _amount) public onlyPayloadSize(3 * 32) returns (bool) {
require(allowances[_from][msg.sender] >= _amount && balances[_from] >= _amount);
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
}
/**
* Allows another account to spend a given amount of tokens on behalf of the
* owner's account. If the owner has previously allowed a spender to spend
* tokens on his or her behalf and would like to change the approval amount,
* he or she will first have to set the allowance back to 0 and then update
* the allowance.
*
* @param _spender The address of the spenders account.
* @param _amount The amount of tokens the spender is allowed to spend.
* */
function approve(address _spender, uint256 _amount) public returns (bool) {
require((_amount == 0) || (allowances[msg.sender][_spender] == 0));
allowances[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/**
* Returns the approved allowance from an owners account to a spenders account.
*
* @param _owner The address of the owners account.
* @param _spender The address of the spenders account.
**/
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowances[_owner][_spender];
}
}
contract MintableToken is AdvancedToken {
bool public mintingFinished;
event TokensMinted(address indexed to, uint256 amount);
event MintingFinished();
/**
* Generates new ACO tokens during the ICO, after which the minting period
* will terminate permenantly. This function can only be called by the ICO
* contract.
*
* @param _to The address of the account to mint new tokens to.
* @param _amount The amount of tokens to mint.
* */
function mint(address _to, uint256 _amount) external onlyOwner onlyPayloadSize(2 * 32) returns (bool) {
require(_to != 0x0 && _amount > 0 && !mintingFinished);
balances[_to] = balances[_to].add(_amount);
totalSupply = totalSupply.add(_amount);
Transfer(0x0, _to, _amount);
TokensMinted(_to, _amount);
return true;
}
/**
* Terminates the minting period permenantly. This function can only be called
* by the ICO contract only when the duration of the ICO has ended.
* */
function finishMinting() external onlyOwner {
require(!mintingFinished);
mintingFinished = true;
MintingFinished();
}
/**
* Returns true if the minting period has ended, false otherwhise.
* */
function mintingFinished() public constant returns (bool) {
return mintingFinished;
}
}
contract ACO is MintableToken {
uint8 public decimals;
string public name;
string public symbol;
function ACO() public {
totalSupply = 0;
decimals = 18;
name = "ACO";
symbol = "ACO";
}
}
contract MultiOwnable {
address[2] public owners;
event OwnershipTransferred(address from, address to);
event OwnershipGranted(address to);
function MultiOwnable() public {
owners[0] = 0x1d554c421182a94E2f4cBD833f24682BBe1eeFe8; //R1
owners[1] = 0x0D7a2716466332Fc5a256FF0d20555A44c099453; //R2
}
/**
* Functions with this modifier will only execute if the the function is called by the
* owners of the contract.
* */
modifier onlyOwners {
require(msg.sender == owners[0] || msg.sender == owners[1]);
_;
}
/**
* Trasfers ownership from the owner who executes the function to another given address.
*
* @param _newOwner The address which will be granted ownership.
* */
function transferOwnership(address _newOwner) public onlyOwners {
require(_newOwner != 0x0 && _newOwner != owners[0] && _newOwner != owners[1]);
if (msg.sender == owners[0]) {
OwnershipTransferred(owners[0], _newOwner);
owners[0] = _newOwner;
} else {
OwnershipTransferred(owners[1], _newOwner);
owners[1] = _newOwner;
}
}
}
contract Crowdsale is MultiOwnable {
using SafeMath for uint256;
ACO public ACO_Token;
address public constant MULTI_SIG = 0x3Ee28dA5eFe653402C5192054064F12a42EA709e;
bool public success;
uint256 public rate;
uint256 public rateWithBonus;
uint256 public tokensSold;
uint256 public startTime;
uint256 public endTime;
uint256 public minimumGoal;
uint256 public cap;
uint256[4] private bonusStages;
mapping (address => uint256) investments;
mapping (address => bool) hasAuthorizedWithdrawal;
event TokensPurchased(address indexed by, uint256 amount);
event RefundIssued(address indexed by, uint256 amount);
event FundsWithdrawn(address indexed by, uint256 amount);
event IcoSuccess();
event CapReached();
function Crowdsale() public {
ACO_Token = new ACO();
minimumGoal = 3000 ether;
cap = 87500 ether;
rate = 4000;
startTime = now.add(3 days);
endTime = startTime.add(90 days);
bonusStages[0] = startTime.add(14 days);
for (uint i = 1; i < bonusStages.length; i++) {
bonusStages[i] = bonusStages[i - 1].add(14 days);
}
}
/**
* Fallback function calls the buyTokens function when ETH is sent to this
* contact.
* */
function() public payable {
buyTokens(msg.sender);
}
/**
* Allows investors to buy ACO tokens. Once ETH is sent to this contract,
* the investor will automatically receive tokens.
*
* @param _beneficiary The address the newly minted tokens will be sent to.
* */
function buyTokens(address _beneficiary) public payable {
require(_beneficiary != 0x0 && validPurchase() && weiRaised().sub(msg.value) < cap);
if (this.balance >= minimumGoal && !success) {
success = true;
IcoSuccess();
}
uint256 weiAmount = msg.value;
if (this.balance > cap) {
CapReached();
uint256 toRefund = this.balance.sub(cap);
msg.sender.transfer(toRefund);
weiAmount = weiAmount.sub(toRefund);
}
uint256 tokens = weiAmount.mul(getCurrentRateWithBonus());
ACO_Token.mint(_beneficiary, tokens);
tokensSold = tokensSold.add(tokens);
investments[_beneficiary] = investments[_beneficiary].add(weiAmount);
TokensPurchased(_beneficiary, tokens);
}
/**
* Returns the amount of tokens 1 ETH equates to with the bonus percentage.
* */
function getCurrentRateWithBonus() public returns (uint256) {
rateWithBonus = (rate.mul(getBonusPercentage()).div(100)).add(rate);
return rateWithBonus;
}
/**
* Calculates and returns the bonus percentage based on how early an investment
* is made. If ETH is sent to the contract after the bonus period, the bonus
* percentage will default to 0
* */
function getBonusPercentage() internal view returns (uint256 bonusPercentage) {
uint256 timeStamp = now;
if (timeStamp > bonusStages[3]) {
bonusPercentage = 0;
} else {
bonusPercentage = 25;
for (uint i = 0; i < bonusStages.length; i++) {
if (timeStamp <= bonusStages[i]) {
break;
} else {
bonusPercentage = bonusPercentage.sub(5);
}
}
}
return bonusPercentage;
}
/**
* Returns the current rate 1 ETH equates to including the bonus amount.
* */
function currentRate() public constant returns (uint256) {
return rateWithBonus;
}
/**
* Checks whether an incoming transaction from the buyTokens function is
* valid or not. For a purchase to be valid, investors have to buy tokens
* only during the ICO period and the value being transferred must be greater
* than 0.
* */
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
/**
* Issues a refund to a given address. This function can only be called if
* the duration of the ICO has ended and the minimum goal has not been reached.
*
* @param _addr The address that will receive a refund.
* */
function getRefund(address _addr) public {
if (_addr == 0x0) {
_addr = msg.sender;
}
require(!isSuccess() && hasEnded() && investments[_addr] > 0);
uint256 toRefund = investments[_addr];
investments[_addr] = 0;
_addr.transfer(toRefund);
RefundIssued(_addr, toRefund);
}
/**
* This function can only be called by the onwers of the ICO contract. There
* needs to be 2 approvals, one from each owner. Once two approvals have been
* made, the funds raised will be sent to a multi signature wallet. This
* function cannot be called if the ICO is not a success.
* */
function authorizeWithdrawal() public onlyOwners {
require(hasEnded() && isSuccess() && !hasAuthorizedWithdrawal[msg.sender]);
hasAuthorizedWithdrawal[msg.sender] = true;
if (hasAuthorizedWithdrawal[owners[0]] && hasAuthorizedWithdrawal[owners[1]]) {
FundsWithdrawn(owners[0], this.balance);
MULTI_SIG.transfer(this.balance);
}
}
/**
* Generates newly minted ACO tokens and sends them to a given address. This
* function can only be called by the owners of the ICO contract during the
* minting period.
*
* @param _to The address to mint new tokens to.
* @param _amount The amount of tokens to mint.
* */
function issueBounty(address _to, uint256 _amount) public onlyOwners {
require(_to != 0x0 && _amount > 0);
ACO_Token.mint(_to, _amount);
}
/**
* Terminates the minting period permanently. This function can only be
* executed by the owners of the ICO contract.
* */
function finishMinting() public onlyOwners {
require(hasEnded());
ACO_Token.finishMinting();
}
/**
* Returns the minimum goal of the ICO.
* */
function minimumGoal() public constant returns (uint256) {
return minimumGoal;
}
/**
* Returns the maximum amount of funds the ICO can receive.
* */
function cap() public constant returns (uint256) {
return cap;
}
/**
* Returns the time that the ICO duration will end.
* */
function endTime() public constant returns (uint256) {
return endTime;
}
/**
* Returns the amount of ETH a given address has invested.
*
* @param _addr The address to query the investment of.
* */
function investmentOf(address _addr) public constant returns (uint256) {
return investments[_addr];
}
/**
* Returns true if the duration of the ICO is over.
* */
function hasEnded() public constant returns (bool) {
return now > endTime;
}
/**
* Returns true if the ICO is a success.
* */
function isSuccess() public constant returns (bool) {
return success;
}
/**
* Returns the amount of ETH raised in wei.
* */
function weiRaised() public constant returns (uint256) {
return this.balance;
}
} | Allows investors to buy ACO tokens. Once ETH is sent to this contract, the investor will automatically receive tokens. _beneficiary The address the newly minted tokens will be sent to. / | function buyTokens(address _beneficiary) public payable {
require(_beneficiary != 0x0 && validPurchase() && weiRaised().sub(msg.value) < cap);
if (this.balance >= minimumGoal && !success) {
success = true;
IcoSuccess();
}
uint256 weiAmount = msg.value;
if (this.balance > cap) {
CapReached();
uint256 toRefund = this.balance.sub(cap);
msg.sender.transfer(toRefund);
weiAmount = weiAmount.sub(toRefund);
}
uint256 tokens = weiAmount.mul(getCurrentRateWithBonus());
ACO_Token.mint(_beneficiary, tokens);
tokensSold = tokensSold.add(tokens);
investments[_beneficiary] = investments[_beneficiary].add(weiAmount);
TokensPurchased(_beneficiary, tokens);
}
| 5,524,526 |
./full_match/80001/0x2d4d7626Fa364C96F70Ea70742f225f24A480E58/sources/contracts/RETA.sol | Sets the fee percentage for the RETA Community fund | function setCommunityFee(uint256 fee, uint256 feeDecimals) public onlyAdmin {
require(fee >= 0, "The RETA Community fee must be greater than 0");
communityFee = fee;
communityFeeDecimals = feeDecimals;
}
| 9,505,656 |
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// 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/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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @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 alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/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;
// 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/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/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}. 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 { }
}
// 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: contracts/HashScapes.sol
// contracts/HashScapes.sol
//
pragma solidity ^0.8.0;
// Inspired/Copied fromm BGANPUNKS V2 (bastardganpunks.club)
contract HashScapes is ERC721Enumerable, Ownable {
using SafeMath for uint256;
uint public constant MAX_SCAPES = 7778;
uint public constant numReserved = 70;
uint private curIndex = 71;
bool public hasSaleStarted = false;
string public METADATA_PROVENANCE_HASH = "";
string public baseURL = "";
constructor() ERC721("HashScapes","HASHSCAPES") {
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function calculatePrice(uint256 cur_id) public view returns (uint256) {
require(hasSaleStarted, "Sale hasn't started");
require(curIndex < MAX_SCAPES, "Sale has already ended");
uint currentSupply = cur_id;
if (currentSupply <= 270) {
return 10000000000000000; //0.01
} else if (currentSupply <= 470) {
return 20000000000000000; //0.02
} else if (currentSupply <= 670) {
return 40000000000000000; //0.04
} else if (currentSupply <= 2171) {
return 80000000000000000; //0.08
} else if (currentSupply <= 4423) {
return 160000000000000000; //0.16
} else if (currentSupply <= 6676) {
return 320000000000000000; //0.32
} else if (currentSupply <= 7678) {
return 640000000000000000; //0.64
} else {
return 1000000000000000000; //1
}
}
function buyScape(uint256 numScapes) public payable {
require(hasSaleStarted, "Sale isn't active");
require(totalSupply() < MAX_SCAPES, "Sale has already ended");
require(numScapes > 0 && numScapes <= 20, "You can buy a maximum of 20 scapes at a time");
require(totalSupply().add(numScapes) <= MAX_SCAPES, "All scapes are sold!");
uint totalPrice = 0; //calculates total price, keeping in mind purchases that span across prices
for (uint i = 0; i < numScapes; i++) {
totalPrice += calculatePrice(curIndex + i);
}
require(msg.value >= totalPrice, "Ether value sent is below the price");
for (uint i = 0; i < numScapes; i++) {
uint mintIndex = curIndex;
_safeMint(msg.sender, mintIndex);
adjustIndex();
}
}
//skip % 1111 == 0 since they are already reserved
function adjustIndex() private {
curIndex++;
if (curIndex % 1111 == 0) {
curIndex++;
}
}
function getCurrentIndex() public view returns (uint) {
return curIndex;
}
function setProvenanceHash(string memory _hash) public onlyOwner {
METADATA_PROVENANCE_HASH = _hash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseURL = baseURI;
}
function startSale() public onlyOwner {
hasSaleStarted = true;
}
function pauseSale() public onlyOwner {
hasSaleStarted = false;
}
function withdrawAll() public payable onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
function reserve() public onlyOwner {
//reserve first 70, and all those INDEX % 1111 == 0
for (uint i = 1; i <= 70; i++) {
_safeMint(owner(), i);
}
for (uint i = 0; i <= MAX_SCAPES; i += 1111) {
_safeMint(owner(), i);
}
}
function reserveCur() public onlyOwner {
//reserves current scape
require(totalSupply() < MAX_SCAPES, "Sale has already ended");
_safeMint(owner(), curIndex);
adjustIndex();
}
} | reserves current scape | function reserveCur() public onlyOwner {
require(totalSupply() < MAX_SCAPES, "Sale has already ended");
_safeMint(owner(), curIndex);
adjustIndex();
}
| 6,045,395 |
/**
*Submitted for verification at Etherscan.io on 2021-04-11
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
/*******************************************************
* Interfaces *
*******************************************************/
interface IV2Vault {
function token() external view returns (address);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function apiVersion() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function emergencyShutdown() external view returns (bool);
function depositLimit() external view returns (uint256);
}
interface IV2Registry {
function numTokens() external view returns (uint256);
function numVaults(address token) external view returns (uint256);
function tokens(uint256 tokenIdx) external view returns (address);
function latestVault(address token) external view returns (address);
function vaults(address token, uint256 tokenIdx)
external
view
returns (address);
}
interface IOracle {
function getNormalizedValueUsdc(address tokenAddress, uint256 amount)
external
view
returns (uint256);
}
interface IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function balanceOf(address account) external view returns (uint256);
function allowance(address spender, address owner)
external
view
returns (uint256);
}
interface IHelper {
// Strategies helper
function assetStrategiesDelegatedBalance(address)
external
view
returns (uint256);
// Allowances helper
struct Allowance {
address owner;
address spender;
uint256 amount;
address token;
}
function allowances(
address ownerAddress,
address[] memory tokensAddresses,
address[] memory spenderAddresses
) external view returns (Allowance[] memory);
}
interface ManagementList {
function isManager(address accountAddress) external returns (bool);
}
/*******************************************************
* Management List *
*******************************************************/
contract Manageable {
ManagementList public managementList;
constructor(address _managementListAddress) {
managementList = ManagementList(_managementListAddress);
}
modifier onlyManagers() {
bool isManager = managementList.isManager(msg.sender);
require(isManager, "ManagementList: caller is not a manager");
_;
}
}
/*******************************************************
* Adapter Logic *
*******************************************************/
contract RegisteryAdapterV2Vault is Manageable {
/*******************************************************
* Common code shared by all adapters *
*******************************************************/
IOracle public oracle; // The oracle is used to fetch USDC normalized pricing data
IV2Registry public registry; // The registry is used to fetch the list of vaults and migration data
IHelper public helper; // A helper utility is used for batch allowance fetching and address array merging
address[] public positionSpenderAddresses; // A settable list of spender addresses with which to fetch asset allowances
mapping(address => bool) public assetDeprecated; // Support for deprecating assets. If an asset is deprecated it will not appear is results
uint256 public numberOfDeprecatedAssets; // Used to keep track of the number of deprecated assets for an adapter
/**
* High level static information about an asset
*/
struct AssetStatic {
address id; // Asset address
string typeId; // Asset typeId (for example "VAULT_V2" or "IRON_BANK_MARKET")
string name; // Asset Name
string version; // Asset version
Token token; // Static asset underlying token information
}
/**
* High level dynamic information about an asset
*/
struct AssetDynamic {
address id; // Asset address
string typeId; // Asset typeId (for example "VAULT_V2" or "IRON_BANK_MARKET")
address tokenId; // Underlying token address;
TokenAmount underlyingTokenBalance; // Underlying token balances
TokenAmount delegatedBalance; // Delegated balances
AssetMetadata metadata; // Metadata specific to the asset type of this adapter
}
/**
* Static token data
*/
struct Token {
address id; // token address
string name; // token name
string symbol; // token symbol
uint8 decimals; // token decimals
}
/**
* Information about a user's position relative to an asset
*/
struct Position {
address assetId; // Asset address
address tokenId; // Underlying asset token address
string typeId; // Position typeId (for example "DEPOSIT," "BORROW," "LEND")
uint256 balance; // asset.balanceOf(account)
TokenAmount accountTokenBalance; // User account balance of underlying token (token.balanceOf(account))
TokenAmount underlyingTokenBalance; // Represents a user's asset position in underlying tokens
Allowance[] tokenAllowances; // Underlying token allowances
Allowance[] assetAllowances; // Asset allowances
}
/**
* Token amount representation
*/
struct TokenAmount {
uint256 amount; // Amount in underlying token decimals
uint256 amountUsdc; // Amount in USDC (6 decimals)
}
/**
* Allowance information
*/
struct Allowance {
address owner; // Allowance owner
address spender; // Allowance spender
uint256 amount; // Allowance amount (in underlying token)
}
/**
* Information about the adapter
*/
struct AdapterInfo {
address id; // Adapter address
string typeId; // Adapter typeId (for example "VAULT_V2" or "IRON_BANK_MARKET")
string categoryId; // Adapter categoryId (for example "VAULT")
}
/**
* Fetch static information about an array of assets. This method can be used for off-chain pagination.
*/
function assetsStatic(address[] memory _assetsAddresses)
public
view
returns (AssetStatic[] memory)
{
uint256 numberOfAssets = _assetsAddresses.length;
AssetStatic[] memory _assets = new AssetStatic[](numberOfAssets);
for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) {
address assetAddress = _assetsAddresses[assetIdx];
AssetStatic memory _asset = assetStatic(assetAddress);
_assets[assetIdx] = _asset;
}
return _assets;
}
/**
* Fetch dynamic information about an array of assets. This method can be used for off-chain pagination.
*/
function assetsDynamic(address[] memory _assetsAddresses)
public
view
returns (AssetDynamic[] memory)
{
uint256 numberOfAssets = _assetsAddresses.length;
AssetDynamic[] memory _assets = new AssetDynamic[](numberOfAssets);
for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) {
address assetAddress = _assetsAddresses[assetIdx];
AssetDynamic memory _asset = assetDynamic(assetAddress);
_assets[assetIdx] = _asset;
}
return _assets;
}
/**
* Fetch static information for all assets
*/
function assetsStatic() external view returns (AssetStatic[] memory) {
address[] memory _assetsAddresses = assetsAddresses();
return assetsStatic(_assetsAddresses);
}
/**
* Fetch dynamic information for all assets
*/
function assetsDynamic() external view returns (AssetDynamic[] memory) {
address[] memory _assetsAddresses = assetsAddresses();
return assetsDynamic(_assetsAddresses);
}
/**
* Fetch underlying token allowances relative to an asset.
* This is useful for determining whether or not a user has token approvals
* to allow depositing into an asset
*/
function tokenAllowances(
address accountAddress,
address tokenAddress,
address assetAddress
) public view returns (Allowance[] memory) {
address[] memory tokenAddresses = new address[](1);
address[] memory assetAddresses = new address[](1);
tokenAddresses[0] = tokenAddress;
assetAddresses[0] = assetAddress;
bytes memory allowances =
abi.encode(
helper.allowances(
accountAddress,
tokenAddresses,
assetAddresses
)
);
return abi.decode(allowances, (Allowance[]));
}
/**
* Fetch asset allowances based on positionSpenderAddresses (configurable).
* This is useful to determine if a particular zap contract is approved for the asset (zap out use case)
*/
function assetAllowances(address accountAddress, address assetAddress)
public
view
returns (Allowance[] memory)
{
address[] memory assetAddresses = new address[](1);
assetAddresses[0] = assetAddress;
bytes memory allowances =
abi.encode(
helper.allowances(
accountAddress,
assetAddresses,
positionSpenderAddresses
)
);
return abi.decode(allowances, (Allowance[]));
}
/**
* Fetch basic static token metadata
*/
function tokenMetadata(address tokenAddress)
internal
view
returns (Token memory)
{
IERC20 _token = IERC20(tokenAddress);
return
Token({
id: tokenAddress,
name: _token.name(),
symbol: _token.symbol(),
decimals: _token.decimals()
});
}
/**
* Deprecate or undeprecate an asset. Deprecated assets will not appear in any adapter method call response
*/
function setAssetDeprecated(address assetAddress, bool newDeprecationStatus)
public
onlyManagers
{
bool currentDeprecationStatus = assetDeprecated[assetAddress];
if (currentDeprecationStatus == newDeprecationStatus) {
revert("Adapter: Unable to change asset deprecation status");
}
if (newDeprecationStatus == true) {
numberOfDeprecatedAssets++;
} else {
numberOfDeprecatedAssets--;
}
assetDeprecated[assetAddress] = newDeprecationStatus;
}
/**
* Set position spender addresses. Used by `assetAllowances(address,address)`.
*/
function setPositionSpenderAddresses(address[] memory addresses)
public
onlyManagers
{
positionSpenderAddresses = addresses;
}
/**
* Fetch TVL for adapter
*/
function assetsTvl() external view returns (uint256) {
uint256 tvl;
address[] memory assetAddresses = assetsAddresses();
uint256 numberOfAssets = assetAddresses.length;
for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) {
address assetAddress = assetAddresses[assetIdx];
uint256 _assetTvl = assetTvl(assetAddress);
tvl += _assetTvl;
}
return tvl;
}
/**
* Configure adapter
*/
constructor(
address _registryAddress,
address _oracleAddress,
address _managementListAddress,
address _helperAddress
) Manageable(_managementListAddress) {
require(
_managementListAddress != address(0),
"Missing management list address"
);
require(_registryAddress != address(0), "Missing registry address");
require(_oracleAddress != address(0), "Missing oracle address");
registry = IV2Registry(_registryAddress);
oracle = IOracle(_oracleAddress);
helper = IHelper(_helperAddress);
}
/*******************************************************
* Common code shared by v1 vaults, v2 vaults and earn *
*******************************************************/
/**
* Fetch asset positions of an account given an array of assets. This method can be used for off-chain pagination.
*/
function positionsOf(
address accountAddress,
address[] memory _assetsAddresses
) public view returns (Position[] memory) {
uint256 numberOfAssets = _assetsAddresses.length;
Position[] memory positions = new Position[](numberOfAssets);
for (uint256 assetIdx = 0; assetIdx < numberOfAssets; assetIdx++) {
address assetAddress = _assetsAddresses[assetIdx];
Position memory position = positionOf(accountAddress, assetAddress);
positions[assetIdx] = position;
}
return positions;
}
/**
* Fetch asset positins for an account for all assets
*/
function positionsOf(address accountAddress)
external
view
returns (Position[] memory)
{
address[] memory _assetsAddresses = assetsAddresses();
return positionsOf(accountAddress, _assetsAddresses);
}
/*******************************************************
* V2 Adapter (unique logic) *
*******************************************************/
/**
* Return information about the adapter
*/
function adapterInfo() public view returns (AdapterInfo memory) {
return
AdapterInfo({
id: address(this),
typeId: "VAULT_V2",
categoryId: "VAULT"
});
}
/**
* Metadata specific to this asset type
*/
struct AssetMetadata {
string symbol; // Vault symbol
uint256 pricePerShare; // Vault pricePerShare
bool migrationAvailable; // True if a migration is available for this vault
address latestVaultAddress; // Latest vault migration address
uint256 depositLimit; // Deposit limit of asset
bool emergencyShutdown; // Vault is in emergency shutdown mode
}
/**
* Fetch the underlying token address of an asset
*/
function underlyingTokenAddress(address assetAddress)
public
view
returns (address)
{
IV2Vault vault = IV2Vault(assetAddress);
address tokenAddress = vault.token();
return tokenAddress;
}
/**
* Fetch the total number of assets for this adapter
*/
function assetsLength() public view returns (uint256) {
uint256 numTokens = registry.numTokens();
uint256 numVaults;
for (uint256 tokenIdx = 0; tokenIdx < numTokens; tokenIdx++) {
address currentToken = registry.tokens(tokenIdx);
uint256 numVaultsForToken = registry.numVaults(currentToken);
numVaults += numVaultsForToken;
}
return numVaults - numberOfDeprecatedAssets;
}
/**
* Fetch all asset addresses for this adapter
*/
function assetsAddresses() public view returns (address[] memory) {
uint256 numVaults = assetsLength();
address[] memory _assetsAddresses = new address[](numVaults);
uint256 numTokens = registry.numTokens();
uint256 currentVaultIdx;
for (uint256 tokenIdx = 0; tokenIdx < numTokens; tokenIdx++) {
address currentTokenAddress = registry.tokens(tokenIdx);
uint256 numVaultsForToken = registry.numVaults(currentTokenAddress);
for (
uint256 vaultTokenIdx = 0;
vaultTokenIdx < numVaultsForToken;
vaultTokenIdx++
) {
address currentAssetAddress =
registry.vaults(currentTokenAddress, vaultTokenIdx);
bool assetIsNotDeprecated =
assetDeprecated[currentAssetAddress] == false;
if (assetIsNotDeprecated) {
_assetsAddresses[currentVaultIdx] = currentAssetAddress;
currentVaultIdx++;
}
}
}
return _assetsAddresses;
}
/**
* Fetch static information about an asset
*/
function assetStatic(address assetAddress)
public
view
returns (AssetStatic memory)
{
IV2Vault vault = IV2Vault(assetAddress);
address tokenAddress = underlyingTokenAddress(assetAddress);
return
AssetStatic({
id: assetAddress,
typeId: adapterInfo().typeId,
name: vault.name(),
version: vault.apiVersion(),
token: tokenMetadata(tokenAddress)
});
}
/**
* Fetch dynamic information about an asset
*/
function assetDynamic(address assetAddress)
public
view
returns (AssetDynamic memory)
{
IV2Vault vault = IV2Vault(assetAddress);
address tokenAddress = underlyingTokenAddress(assetAddress);
uint256 totalSupply = vault.totalSupply();
uint256 pricePerShare = 0;
bool vaultHasShares = totalSupply != 0;
if (vaultHasShares) {
pricePerShare = vault.pricePerShare();
}
address latestVaultAddress = registry.latestVault(tokenAddress);
bool migrationAvailable = latestVaultAddress != assetAddress;
AssetMetadata memory metadata =
AssetMetadata({
symbol: vault.symbol(),
pricePerShare: pricePerShare,
migrationAvailable: migrationAvailable,
latestVaultAddress: latestVaultAddress,
depositLimit: vault.depositLimit(),
emergencyShutdown: vault.emergencyShutdown()
});
TokenAmount memory underlyingTokenBalance =
TokenAmount({
amount: assetBalance(assetAddress),
amountUsdc: assetTvl(assetAddress)
});
uint256 delegatedBalanceAmount =
helper.assetStrategiesDelegatedBalance(assetAddress);
TokenAmount memory delegatedBalance =
TokenAmount({
amount: delegatedBalanceAmount,
amountUsdc: oracle.getNormalizedValueUsdc(
tokenAddress,
delegatedBalanceAmount
)
});
return
AssetDynamic({
id: assetAddress,
typeId: adapterInfo().typeId,
tokenId: tokenAddress,
underlyingTokenBalance: underlyingTokenBalance,
delegatedBalance: delegatedBalance,
metadata: metadata
});
}
/**
* Fetch asset position of an account given an asset address
*/
function positionOf(address accountAddress, address assetAddress)
public
view
returns (Position memory)
{
IV2Vault _asset = IV2Vault(assetAddress);
uint8 assetDecimals = _asset.decimals();
address tokenAddress = underlyingTokenAddress(assetAddress);
IERC20 token = IERC20(tokenAddress);
uint256 balance = _asset.balanceOf(accountAddress);
uint256 _accountTokenBalance =
(balance * _asset.pricePerShare()) / 10**assetDecimals;
uint256 _underlyingTokenBalance = token.balanceOf(accountAddress);
return
Position({
assetId: assetAddress,
tokenId: tokenAddress,
typeId: "deposit",
balance: balance,
underlyingTokenBalance: TokenAmount({
amount: _underlyingTokenBalance,
amountUsdc: oracle.getNormalizedValueUsdc(
tokenAddress,
_underlyingTokenBalance
)
}),
accountTokenBalance: TokenAmount({
amount: _accountTokenBalance,
amountUsdc: oracle.getNormalizedValueUsdc(
tokenAddress,
_accountTokenBalance
)
}),
tokenAllowances: tokenAllowances(
accountAddress,
tokenAddress,
assetAddress
),
assetAllowances: assetAllowances(accountAddress, assetAddress)
});
}
/**
* Fetch asset balance in underlying tokens
*/
function assetBalance(address assetAddress) public view returns (uint256) {
IV2Vault vault = IV2Vault(assetAddress);
return vault.totalAssets();
}
/**
* Fetch TVL of an asset
*/
function assetTvl(address assetAddress) public view returns (uint256) {
address tokenAddress = underlyingTokenAddress(assetAddress);
uint256 amount = assetBalance(assetAddress);
uint256 delegatedBalanceAmount =
helper.assetStrategiesDelegatedBalance(assetAddress);
amount -= delegatedBalanceAmount;
uint256 tvl = oracle.getNormalizedValueUsdc(tokenAddress, amount);
return tvl;
}
} | Fetch all asset addresses for this adapter/ | function assetsAddresses() public view returns (address[] memory) {
uint256 numVaults = assetsLength();
address[] memory _assetsAddresses = new address[](numVaults);
uint256 numTokens = registry.numTokens();
uint256 currentVaultIdx;
for (uint256 tokenIdx = 0; tokenIdx < numTokens; tokenIdx++) {
address currentTokenAddress = registry.tokens(tokenIdx);
uint256 numVaultsForToken = registry.numVaults(currentTokenAddress);
for (
uint256 vaultTokenIdx = 0;
vaultTokenIdx < numVaultsForToken;
vaultTokenIdx++
) {
address currentAssetAddress =
registry.vaults(currentTokenAddress, vaultTokenIdx);
bool assetIsNotDeprecated =
assetDeprecated[currentAssetAddress] == false;
if (assetIsNotDeprecated) {
_assetsAddresses[currentVaultIdx] = currentAssetAddress;
currentVaultIdx++;
}
}
}
return _assetsAddresses;
}
| 7,746,574 |
/* solhint-disable func-order */
pragma solidity ^0.4.24;
import "./BimodalLib.sol";
import "./MerkleVerifier.sol";
import "./SafeMath/SafeMathLib32.sol";
import "./SafeMath/SafeMathLib256.sol";
/**
* This library contains the challenge-response implementations of NOCUST.
*/
library ChallengeLib {
using SafeMathLib256 for uint256;
using SafeMathLib32 for uint32;
using BimodalLib for BimodalLib.Ledger;
// EVENTS
event ChallengeIssued(address indexed token, address indexed recipient, address indexed sender);
event StateUpdate(
address indexed token,
address indexed account,
uint256 indexed eon,
uint64 trail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
bytes32 activeStateChecksum,
bytes32 passiveChecksum,
bytes32 r, bytes32 s, uint8 v
);
// Validation
function verifyProofOfExclusiveAccountBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20 token,
address holder,
bytes32[2] activeStateChecksum_passiveTransfersRoot, // solhint-disable func-param-name-mixedcase
uint64 trail,
uint256[3] eonPassiveMark,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2] LR // solhint-disable func-param-name-mixedcase
)
public
view
returns (bool)
{
BimodalLib.Checkpoint memory checkpoint = ledger.checkpoints[eonPassiveMark[0].mod(ledger.EONS_KEPT)];
require(eonPassiveMark[0] == checkpoint.eonNumber, 'r');
// activeStateChecksum is set to the account node.
activeStateChecksum_passiveTransfersRoot[0] = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(holder)),
keccak256(abi.encodePacked(
activeStateChecksum_passiveTransfersRoot[1], // passiveTransfersRoot
eonPassiveMark[1],
eonPassiveMark[2])),
activeStateChecksum_passiveTransfersRoot[0] // activeStateChecksum
));
// the interval allotment is set to form the leaf
activeStateChecksum_passiveTransfersRoot[0] = keccak256(abi.encodePacked(
LR[0], activeStateChecksum_passiveTransfersRoot[0], LR[1]
));
// This calls the merkle verification procedure, which returns the
// checkpoint allotment size
uint64 tokenTrail = ledger.tokenToTrail[token];
LR[0] = MerkleVerifier.verifyProofOfExclusiveBalanceAllotment(
trail,
tokenTrail,
activeStateChecksum_passiveTransfersRoot[0],
checkpoint.merkleRoot,
allotmentChain,
membershipChain,
values,
LR);
// The previous allotment size of the target eon is reconstructed from the
// deposits and withdrawals performed so far and the current balance.
LR[1] = address(this).balance;
if (token != address(this)) {
require(
tokenTrail != 0,
't');
LR[1] = token.balanceOf(this);
}
// Credit back confirmed withdrawals that were performed since target eon
for (tokenTrail = 0; tokenTrail < ledger.EONS_KEPT; tokenTrail++) {
if (ledger.confirmedWithdrawals[token][tokenTrail].eon >= eonPassiveMark[0]) {
LR[1] = LR[1].add(ledger.confirmedWithdrawals[token][tokenTrail].amount);
}
}
// Debit deposits performed since target eon
for (tokenTrail = 0; tokenTrail < ledger.EONS_KEPT; tokenTrail++) {
if (ledger.deposits[token][tokenTrail].eon >= eonPassiveMark[0]) {
LR[1] = LR[1].sub(ledger.deposits[token][tokenTrail].amount);
}
}
// Debit withdrawals pending since prior eon
LR[1] = LR[1].sub(ledger.getPendingWithdrawalsAtEon(token, eonPassiveMark[0].sub(1)));
// Require that the reconstructed allotment matches the proof allotment
require(
LR[0] <= LR[1],
'b');
return true;
}
function verifyProofOfActiveStateUpdateAgreement(
ERC20 token,
address holder,
uint64 trail,
uint256 eon,
bytes32 txSetRoot,
uint256[2] deltas,
address attester,
bytes32 r,
bytes32 s,
uint8 v
)
public
view
returns (bytes32 checksum)
{
checksum = MerkleVerifier.activeStateUpdateChecksum(token, holder, trail, eon, txSetRoot, deltas);
require(attester == BimodalLib.signedMessageECRECOVER(checksum, r, s, v), 'A');
}
function verifyWithdrawalAuthorization(
ERC20 token,
address holder,
uint256 expiry,
uint256 amount,
address attester,
bytes32 r,
bytes32 s,
uint8 v
)
public
view
returns (bool)
{
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(holder)),
expiry,
amount));
require(attester == BimodalLib.signedMessageECRECOVER(checksum, r, s, v), 'a');
return true;
}
// Challenge Lifecycle Methods
/**
* This method increments the live challenge counter and emits and event
* containing the challenge index.
*/
function markChallengeLive(
BimodalLib.Ledger storage ledger,
ERC20 token,
address recipient,
address sender
)
private
{
require(ledger.currentEra() > ledger.BLOCKS_PER_EPOCH);
uint256 eon = ledger.currentEon();
BimodalLib.Checkpoint storage checkpoint = ledger.getOrCreateCheckpoint(eon, eon);
checkpoint.liveChallenges = checkpoint.liveChallenges.add(1);
emit ChallengeIssued(token, recipient, sender);
}
/**
* This method clears all the data in a Challenge structure and decrements the
* live challenge counter.
*/
function clearChallenge(
BimodalLib.Ledger storage ledger,
BimodalLib.Challenge storage challenge
)
private
{
BimodalLib.Checkpoint storage checkpoint = ledger.getOrCreateCheckpoint(
challenge.initialStateEon.add(1),
ledger.currentEon());
checkpoint.liveChallenges = checkpoint.liveChallenges.sub(1);
challenge.challengeType = BimodalLib.ChallengeType.NONE;
challenge.block = 0;
// challenge.initialStateEon = 0;
challenge.initialStateBalance = 0;
challenge.deltaHighestSpendings = 0;
challenge.deltaHighestGains = 0;
challenge.finalStateBalance = 0;
challenge.deliveredTxNonce = 0;
challenge.trailIdentifier = 0;
}
/**
* This method marks a challenge as having been successfully answered only if
* the response was provided in time.
*/
function markChallengeAnswered(
BimodalLib.Ledger storage ledger,
BimodalLib.Challenge storage challenge
)
private
{
uint256 eon = ledger.currentEon();
require(
challenge.challengeType != BimodalLib.ChallengeType.NONE &&
block.number.sub(challenge.block) < ledger.BLOCKS_PER_EPOCH &&
(
challenge.initialStateEon == eon.sub(1) ||
(challenge.initialStateEon == eon.sub(2) && ledger.currentEra() < ledger.BLOCKS_PER_EPOCH)
)
);
clearChallenge(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== STATE UPDATE Challenge
// ========================================================================
// ========================================================================
// ========================================================================
/**
* This method initiates the fields of the Challenge struct to hold a state
* update challenge.
*/
function initStateUpdateChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
uint256 owed,
uint256[2] spentGained,
uint64 trail
)
private
{
BimodalLib.Challenge storage challengeEntry = ledger.challengeBook[token][msg.sender][msg.sender];
require(challengeEntry.challengeType == BimodalLib.ChallengeType.NONE);
require(challengeEntry.initialStateEon < ledger.currentEon().sub(1));
challengeEntry.initialStateEon = ledger.currentEon().sub(1);
challengeEntry.initialStateBalance = owed;
challengeEntry.deltaHighestSpendings = spentGained[0];
challengeEntry.deltaHighestGains = spentGained[1];
challengeEntry.trailIdentifier = trail;
challengeEntry.challengeType = BimodalLib.ChallengeType.STATE_UPDATE;
challengeEntry.block = block.number;
markChallengeLive(ledger, token, msg.sender, msg.sender);
}
/**
* This method checks that the updated balance is at least as much as the
* expected balance.
*/
function checkStateUpdateBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
BimodalLib.Challenge storage challenge,
uint256[2] LR, // solhint-disable func-param-name-mixedcase
uint256[2] spentGained,
uint256 passivelyReceived
)
private
view
{
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(token, msg.sender);
uint256 incoming = spentGained[1] // actively received in commit chain
.add(deposits)
.add(passivelyReceived);
uint256 outgoing = spentGained[0] // actively spent in commit chain
.add(withdrawals);
// This verification is modified to permit underflow of expected balance
// since a client can choose to zero the `challenge.initialStateBalance`
require(
challenge.initialStateBalance
.add(incoming)
<=
LR[1].sub(LR[0]) // final balance allotment
.add(outgoing)
,
'B');
}
function challengeStateUpdateWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32[2] checksums,
uint64 trail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] value,
uint256[2][3] lrDeltasPassiveMark,
bytes32[3] rsTxSetRoot,
uint8 v
)
public
/* payable */
/* onlyWithFairReimbursement(ledger) */
{
uint256 previousEon = ledger.currentEon().sub(1);
address operator = ledger.operator;
// The hub must have committed to this state update
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) {
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
previousEon,
rsTxSetRoot[2],
lrDeltasPassiveMark[1],
operator,
rsTxSetRoot[0], rsTxSetRoot[1], v);
}
initStateUpdateChallenge(
ledger,
token,
lrDeltasPassiveMark[0][1].sub(lrDeltasPassiveMark[0][0]),
lrDeltasPassiveMark[1],
trail);
// The initial state must have been ratified in the commitment
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
msg.sender,
checksums,
trail,
[previousEon, lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
value,
lrDeltasPassiveMark[0]));
}
function challengeStateUpdateWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32 txSetRoot,
uint64 trail,
uint256[2] deltas,
bytes32 r,
bytes32 s,
uint8 v
)
public
/* payable */
/* TODO calculate exact addition */
/* onlyWithSkewedReimbursement(ledger, 25) */
{
// The hub must have committed to this transition
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
ledger.currentEon().sub(1),
txSetRoot,
deltas,
ledger.operator,
r, s, v);
initStateUpdateChallenge(ledger, token, 0, deltas, trail);
}
function answerStateUpdateChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
address issuer,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark, // [ [L, R], Deltas ]
bytes32[6] rSrStxSetRootChecksum,
uint8[2] v
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.STATE_UPDATE);
// Transition must have been approved by issuer
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) {
rSrStxSetRootChecksum[0] = verifyProofOfActiveStateUpdateAgreement(
token,
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
rSrStxSetRootChecksum[4], // txSetRoot
lrDeltasPassiveMark[1], // deltas
issuer,
rSrStxSetRootChecksum[0], // R[0]
rSrStxSetRootChecksum[1], // S[0]
v[0]);
address operator = ledger.operator;
rSrStxSetRootChecksum[1] = verifyProofOfActiveStateUpdateAgreement(
token,
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
rSrStxSetRootChecksum[4], // txSetRoot
lrDeltasPassiveMark[1], // deltas
operator,
rSrStxSetRootChecksum[2], // R[1]
rSrStxSetRootChecksum[3], // S[1]
v[1]);
require(rSrStxSetRootChecksum[0] == rSrStxSetRootChecksum[1], 'u');
} else {
rSrStxSetRootChecksum[0] = bytes32(0);
}
// Transition has to be at least as recent as submitted one
require(
lrDeltasPassiveMark[1][0] >= challenge.deltaHighestSpendings &&
lrDeltasPassiveMark[1][1] >= challenge.deltaHighestGains,
'x');
// Transition has to have been properly applied
checkStateUpdateBalance(
ledger,
token,
challenge,
lrDeltasPassiveMark[0], // LR
lrDeltasPassiveMark[1], // deltas
lrDeltasPassiveMark[2][0]); // passive amount
// Truffle crashes when trying to interpret this event in some cases.
emit StateUpdate(
token,
issuer,
challenge.initialStateEon.add(1),
challenge.trailIdentifier,
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark,
rSrStxSetRootChecksum[0], // activeStateChecksum
rSrStxSetRootChecksum[5], // passiveAcceptChecksum
rSrStxSetRootChecksum[2], // R[1]
rSrStxSetRootChecksum[3], // S[1]
v[1]);
// Proof of stake must be ratified in the checkpoint
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
issuer,
[rSrStxSetRootChecksum[0], rSrStxSetRootChecksum[5]], // activeStateChecksum, passiveAcceptChecksum
challenge.trailIdentifier,
[
challenge.initialStateEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1]
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0]), // LR
'c');
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== ACTIVE DELIVERY Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function initTransferDeliveryChallenge(
BimodalLib.Ledger storage ledger,
ERC20 token,
address sender,
address recipient,
uint256 amount,
uint256 txNonce,
uint64 trail
)
private
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][recipient][sender];
require(challenge.challengeType == BimodalLib.ChallengeType.NONE);
require(challenge.initialStateEon < ledger.currentEon().sub(1));
challenge.challengeType = BimodalLib.ChallengeType.TRANSFER_DELIVERY;
challenge.initialStateEon = ledger.currentEon().sub(1);
challenge.deliveredTxNonce = txNonce;
challenge.block = block.number;
challenge.trailIdentifier = trail;
challenge.finalStateBalance = amount;
markChallengeLive(
ledger,
token,
recipient,
sender);
}
function challengeTransferDeliveryWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint256[2] nonceAmount,
uint64[3] trails,
bytes32[] chain,
uint256[2] deltas,
bytes32[3] rsTxSetRoot,
uint8 v
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
require(msg.sender == SR[0] || msg.sender == SR[1], 'd');
// Require hub to have committed to transition
verifyProofOfActiveStateUpdateAgreement(
token,
SR[0],
trails[0],
ledger.currentEon().sub(1),
rsTxSetRoot[2],
deltas,
ledger.operator,
rsTxSetRoot[0], rsTxSetRoot[1], v);
rsTxSetRoot[0] = MerkleVerifier.transferChecksum(
SR[1],
nonceAmount[1], // amount
trails[2],
nonceAmount[0]); // nonce
// Require tx to exist in transition
require(MerkleVerifier.verifyProofOfMembership(
trails[1],
chain,
rsTxSetRoot[0], // transferChecksum
rsTxSetRoot[2]), // txSetRoot
'e');
initTransferDeliveryChallenge(
ledger,
token,
SR[0], // senderAddress
SR[1], // recipientAddress
nonceAmount[1], // amount
nonceAmount[0], // nonce
trails[2]); // recipientTrail
}
function answerTransferDeliveryChallengeWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
bytes32[2] txSetRootChecksum,
bytes32[] txChain
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][SR[1]][SR[0]];
require(challenge.challengeType == BimodalLib.ChallengeType.TRANSFER_DELIVERY);
// Assert that the challenged transaction belongs to the transfer set
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
MerkleVerifier.transferChecksum(
SR[0],
challenge.finalStateBalance, // amount
challenge.trailIdentifier, // recipient trail
challenge.deliveredTxNonce),
txSetRootChecksum[0])); // txSetRoot
// Require committed transition to include transfer
txSetRootChecksum[0] = MerkleVerifier.activeStateUpdateChecksum(
token,
SR[1],
challenge.trailIdentifier,
challenge.initialStateEon,
txSetRootChecksum[0], // txSetRoot
lrDeltasPassiveMark[1]); // Deltas
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[1], // recipient
txSetRootChecksum, // [activeStateChecksum, passiveChecksum]
challenge.trailIdentifier,
[
challenge.initialStateEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0])); // LR
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== PASSIVE DELIVERY Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function challengeTransferDeliveryWithProofOfPassiveStateUpdate(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
bytes32[2] txSetRootChecksum,
uint64[3] senderTransferRecipientTrails,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][4] lrDeltasPassiveMarkDummyAmount,
bytes32[] transferMembershipChain
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
require(msg.sender == SR[0] || msg.sender == SR[1], 'd');
lrDeltasPassiveMarkDummyAmount[3][0] = ledger.currentEon().sub(1); // previousEon
// Assert that the challenged transaction ends the transfer set
require(MerkleVerifier.verifyProofOfMembership(
senderTransferRecipientTrails[1], // transferMembershipTrail
transferMembershipChain,
MerkleVerifier.transferChecksum(
SR[1], // recipientAddress
lrDeltasPassiveMarkDummyAmount[3][1], // amount
senderTransferRecipientTrails[2], // recipientTrail
2 ** 256 - 1), // nonce
txSetRootChecksum[0]), // txSetRoot
'e');
// Require committed transition to include transfer
txSetRootChecksum[0] = MerkleVerifier.activeStateUpdateChecksum(
token,
SR[0], // senderAddress
senderTransferRecipientTrails[0], // senderTrail
lrDeltasPassiveMarkDummyAmount[3][0], // previousEon
txSetRootChecksum[0], // txSetRoot
lrDeltasPassiveMarkDummyAmount[1]); // Deltas
// Assert that this transition was used to update the sender's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[0], // senderAddress
txSetRootChecksum, // [activeStateChecksum, passiveChecksum]
senderTransferRecipientTrails[0], // senderTrail
[
lrDeltasPassiveMarkDummyAmount[3][0].add(1), // eonNumber
lrDeltasPassiveMarkDummyAmount[2][0], // passiveAmount
lrDeltasPassiveMarkDummyAmount[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMarkDummyAmount[0])); // LR
initTransferDeliveryChallenge(
ledger,
token,
SR[0], // sender
SR[1], // recipient
lrDeltasPassiveMarkDummyAmount[3][1], // amount
uint256(keccak256(abi.encodePacked(lrDeltasPassiveMarkDummyAmount[2][1], uint256(2 ** 256 - 1)))), // mark (nonce)
senderTransferRecipientTrails[2]); // recipientTrail
}
function answerTransferDeliveryChallengeWithProofOfPassiveStateUpdate(
BimodalLib.Ledger storage ledger,
ERC20 token,
address[2] SR, // solhint-disable func-param-name-mixedcase
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
uint256[] values,
uint256[2][3] lrPassiveMarkPositionNonce,
bytes32[2] checksums,
bytes32[] txChainValues
)
public
{
BimodalLib.Challenge storage challenge = ledger.challengeBook[token][SR[1]][SR[0]];
require(challenge.challengeType == BimodalLib.ChallengeType.TRANSFER_DELIVERY);
require(
challenge.deliveredTxNonce ==
uint256(keccak256(abi.encodePacked(lrPassiveMarkPositionNonce[2][0], lrPassiveMarkPositionNonce[2][1])))
);
// Assert that the challenged transaction belongs to the passively delivered set
require(
MerkleVerifier.verifyProofOfPassiveDelivery(
transferMembershipTrail,
MerkleVerifier.transferChecksum( // node
SR[0], // sender
challenge.finalStateBalance, // amount
challenge.trailIdentifier, // recipient trail
challenge.deliveredTxNonce),
checksums[1], // passiveChecksum
txChainValues,
[lrPassiveMarkPositionNonce[2][0], lrPassiveMarkPositionNonce[2][0].add(challenge.finalStateBalance)])
<=
lrPassiveMarkPositionNonce[1][0]);
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
token,
SR[1], // recipient
checksums, // [activeStateChecksum, passiveChecksum]
challenge.trailIdentifier, // recipientTrail
[
challenge.initialStateEon.add(1), // eonNumber
lrPassiveMarkPositionNonce[1][0], // passiveAmount
lrPassiveMarkPositionNonce[1][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrPassiveMarkPositionNonce[0])); // LR
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== SWAP Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function initSwapEnactmentChallenge(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
uint256[4] updatedSpentGainedPassive,
uint256[4] sellBuyBalanceNonce,
uint64 recipientTrail
)
private
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][msg.sender][msg.sender];
require(challenge.challengeType == BimodalLib.ChallengeType.NONE);
require(challenge.initialStateEon < ledger.currentEon().sub(1));
challenge.initialStateEon = ledger.currentEon().sub(1);
challenge.deliveredTxNonce = sellBuyBalanceNonce[3];
challenge.challengeType = BimodalLib.ChallengeType.SWAP_ENACTMENT;
challenge.block = block.number;
challenge.trailIdentifier = recipientTrail;
challenge.deltaHighestSpendings = sellBuyBalanceNonce[0];
challenge.deltaHighestGains = sellBuyBalanceNonce[1];
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(tokens[0], msg.sender);
challenge.initialStateBalance =
sellBuyBalanceNonce[2] // allotment from eon e - 1
.add(updatedSpentGainedPassive[2]) // gained
.add(updatedSpentGainedPassive[3]) // passively delivered
.add(deposits)
.sub(updatedSpentGainedPassive[1]) // spent
.sub(withdrawals);
challenge.finalStateBalance = updatedSpentGainedPassive[0];
require(challenge.finalStateBalance >= challenge.initialStateBalance, 'd');
markChallengeLive(ledger, conduit, msg.sender, msg.sender);
}
function challengeSwapEnactmentWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
uint64[3] senderTransferRecipientTrails, // senderTransferRecipientTrails
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256[4] sellBuyBalanceNonce,
bytes32[3] txSetRootChecksumDummy
)
public
/* payable */
/* onlyWithFairReimbursement() */
{
// Require swap to exist in transition
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
senderTransferRecipientTrails[2],
sellBuyBalanceNonce[0], // sell
sellBuyBalanceNonce[1], // buy
sellBuyBalanceNonce[2], // balance
sellBuyBalanceNonce[3]); // nonce
require(MerkleVerifier.verifyProofOfMembership(
senderTransferRecipientTrails[1],
txChain,
txSetRootChecksumDummy[2], // swapOrderChecksum
txSetRootChecksumDummy[0]), // txSetRoot
'e');
uint256 previousEon = ledger.currentEon().sub(1);
// Require committed transition to include swap
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[0],
msg.sender,
senderTransferRecipientTrails[0],
previousEon,
txSetRootChecksumDummy[0],
lrDeltasPassiveMark[1]); // deltas
uint256 updatedBalance = lrDeltasPassiveMark[0][1].sub(lrDeltasPassiveMark[0][0]);
// The state must have been ratified in the commitment
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
tokens[0],
msg.sender,
[txSetRootChecksumDummy[2], txSetRootChecksumDummy[1]], // [activeStateChecksum, passiveChecksum]
senderTransferRecipientTrails[0],
[
previousEon.add(1), // eonNumber
lrDeltasPassiveMark[2][0], // passiveAmount
lrDeltasPassiveMark[2][1] // passiveMark
],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0])); // LR
initSwapEnactmentChallenge(
ledger,
tokens,
[
updatedBalance, // updated
lrDeltasPassiveMark[1][0], // spent
lrDeltasPassiveMark[1][1], // gained
lrDeltasPassiveMark[2][0]], // passiveAmount
sellBuyBalanceNonce,
senderTransferRecipientTrails[2]);
}
/**
* This method just calculates the total expected balance.
*/
function calculateSwapConsistencyBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
uint256[2] deltas,
uint256 passiveAmount,
uint256 balance
)
private
view
returns (uint256)
{
(uint256 deposits, uint256 withdrawals) = ledger.getCurrentEonDepositsWithdrawals(token, msg.sender);
return balance
.add(deltas[1]) // gained
.add(passiveAmount) // passively delivered
.add(deposits)
.sub(withdrawals)
.sub(deltas[0]); // spent
}
/**
* This method calculates the balance expected to be credited in return for that
* debited in another token according to the swapping price and is adjusted to
* ignore numerical errors up to 2 decimal places.
*/
function verifySwapConsistency(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
BimodalLib.Challenge challenge,
uint256[2] LR, // solhint-disable func-param-name-mixedcase
uint256[2] deltas,
uint256 passiveAmount,
uint256 balance
)
private
view
returns (bool)
{
balance = calculateSwapConsistencyBalance(ledger, tokens[1], deltas, passiveAmount, balance);
require(LR[1].sub(LR[0]) >= balance);
uint256 taken = challenge.deltaHighestSpendings // sell amount
.sub(challenge.finalStateBalance.sub(challenge.initialStateBalance)); // refund
uint256 given = LR[1].sub(LR[0]) // recipient allotment
.sub(balance); // authorized allotment
return taken.mul(challenge.deltaHighestGains).div(100) >= challenge.deltaHighestSpendings.mul(given).div(100);
}
function answerSwapChallengeWithProofOfExclusiveBalanceAllotment(
BimodalLib.Ledger storage ledger,
ERC20[2] tokens,
address issuer,
uint64 transferMembershipTrail,
bytes32[] allotmentChain,
bytes32[] membershipChain,
bytes32[] txChain,
uint256[] values,
uint256[2][3] lrDeltasPassiveMark,
uint256 balance,
bytes32[3] txSetRootChecksumDummy
)
public
{
ERC20 conduit = ERC20(address(keccak256(abi.encodePacked(tokens[0], tokens[1]))));
BimodalLib.Challenge storage challenge = ledger.challengeBook[conduit][issuer][issuer];
require(challenge.challengeType == BimodalLib.ChallengeType.SWAP_ENACTMENT);
// Assert that the challenged swap belongs to the transition
txSetRootChecksumDummy[2] = MerkleVerifier.swapOrderChecksum(
tokens,
challenge.trailIdentifier, // recipient trail
challenge.deltaHighestSpendings, // sell amount
challenge.deltaHighestGains, // buy amount
balance, // starting balance
challenge.deliveredTxNonce);
require(MerkleVerifier.verifyProofOfMembership(
transferMembershipTrail,
txChain,
txSetRootChecksumDummy[2], // order checksum
txSetRootChecksumDummy[0]), 'M'); // txSetRoot
// Require committed transition to include swap
txSetRootChecksumDummy[2] = MerkleVerifier.activeStateUpdateChecksum(
tokens[1],
issuer,
challenge.trailIdentifier,
challenge.initialStateEon,
txSetRootChecksumDummy[0], // txSetRoot
lrDeltasPassiveMark[1]); // deltas
if (balance != 2 ** 256 - 1) {
require(verifySwapConsistency(
ledger,
tokens,
challenge,
lrDeltasPassiveMark[0],
lrDeltasPassiveMark[1],
lrDeltasPassiveMark[2][0],
balance),
'v');
}
// Assert that this transition was used to update the recipient's stake
require(verifyProofOfExclusiveAccountBalanceAllotment(
ledger,
tokens[1],
issuer,
[txSetRootChecksumDummy[2], txSetRootChecksumDummy[1]], // activeStateChecksum, passiveChecksum
challenge.trailIdentifier,
[challenge.initialStateEon.add(1), lrDeltasPassiveMark[2][0], lrDeltasPassiveMark[2][1]],
allotmentChain,
membershipChain,
values,
lrDeltasPassiveMark[0]), // LR
's');
markChallengeAnswered(ledger, challenge);
}
// ========================================================================
// ========================================================================
// ========================================================================
// ==================================== WITHDRAWAL Challenge
// ========================================================================
// ========================================================================
// ========================================================================
function slashWithdrawalWithProofOfMinimumAvailableBalance(
BimodalLib.Ledger storage ledger,
ERC20 token,
address withdrawer,
uint256[2] markerEonAvailable,
bytes32[2] rs,
uint8 v
)
public
returns (uint256[2] amounts)
{
uint256 latestEon = ledger.currentEon();
require(
latestEon < markerEonAvailable[0].add(3),
'm');
bytes32 checksum = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(address(this))),
keccak256(abi.encodePacked(token)),
keccak256(abi.encodePacked(withdrawer)),
markerEonAvailable[0],
markerEonAvailable[1]
));
require(withdrawer == BimodalLib.signedMessageECRECOVER(checksum, rs[0], rs[1], v));
BimodalLib.Wallet storage entry = ledger.walletBook[token][withdrawer];
BimodalLib.Withdrawal[] storage withdrawals = entry.withdrawals;
for (uint32 i = 1; i <= withdrawals.length; i++) {
BimodalLib.Withdrawal storage withdrawal = withdrawals[withdrawals.length.sub(i)];
if (withdrawal.eon.add(1) < latestEon) {
break;
} else if (withdrawal.eon == latestEon.sub(1)) {
amounts[0] = amounts[0].add(withdrawal.amount);
} else if (withdrawal.eon == latestEon) {
amounts[1] = amounts[1].add(withdrawal.amount);
}
}
require(amounts[0].add(amounts[1]) > markerEonAvailable[1]);
withdrawals.length = withdrawals.length.sub(i.sub(1)); // i >= 1
if (amounts[1] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon, latestEon, amounts[1]);
ledger.appendOperationToEonAccumulator(
latestEon,
token,
withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[1]);
}
if (amounts[0] > 0) {
ledger.deductFromRunningPendingWithdrawals(token, latestEon.sub(1), latestEon, amounts[0]);
ledger.appendOperationToEonAccumulator(
latestEon.sub(1),
token, withdrawer,
BimodalLib.Operation.CANCELLATION,
amounts[0]);
}
}
}
| payable / TODO calculate exact addition / onlyWithSkewedReimbursement(ledger, 25) / The hub must have committed to this transition | function challengeStateUpdateWithProofOfActiveStateUpdateAgreement(
BimodalLib.Ledger storage ledger,
ERC20 token,
bytes32 txSetRoot,
uint64 trail,
uint256[2] deltas,
bytes32 r,
bytes32 s,
uint8 v
)
public
{
verifyProofOfActiveStateUpdateAgreement(
token,
msg.sender,
trail,
ledger.currentEon().sub(1),
txSetRoot,
deltas,
ledger.operator,
r, s, v);
initStateUpdateChallenge(ledger, token, 0, deltas, trail);
}
| 12,584,726 |
pragma solidity ^0.4.21;
contract ERC820Registry {
function getManager(address addr) public view returns(address);
function setManager(address addr, address newManager) public;
function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address);
function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public;
}
contract ERC820Implementer {
ERC820Registry erc820Registry = ERC820Registry(0x991a1bcb077599290d7305493c9A630c20f8b798);
function setInterfaceImplementation(string ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(ifaceLabel);
erc820Registry.setInterfaceImplementer(this, ifaceHash, impl);
}
function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) {
bytes32 ifaceHash = keccak256(ifaceLabel);
return erc820Registry.getInterfaceImplementer(addr, ifaceHash);
}
function delegateManagement(address newManager) internal {
erc820Registry.setManager(this, newManager);
}
}
/**
* @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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// @title ERC777 ReferenceToken Contract
/// @author Jordi Baylina, Jacques Dafflon
/// @dev This token contract's goal is to give an example implementation
/// of ERC777 with ERC20 compatiblity using the base ERC777 and ERC20
/// implementations provided with the erc777 package.
/// This contract does not define any standard, but can be taken as a reference
/// implementation in case of any ambiguity into the standard
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// solhint-disable-next-line compiler-fixed
interface ERC20Token {
function name() public constant returns (string);
function symbol() public constant returns (string);
function decimals() public constant returns (uint8);
function totalSupply() public constant returns (uint256);
function balanceOf(address owner) public constant returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public constant returns (uint256);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// solhint-disable-next-line compiler-fixed
interface ERC777Token {
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function granularity() public view returns (uint256);
function defaultOperators() public view returns (address[]);
function isOperatorFor(address operator, address tokenHolder) public view returns (bool);
function authorizeOperator(address operator) public;
function revokeOperator(address operator) public;
function send(address to, uint256 amount, bytes holderData) public;
function operatorSend(address from, address to, uint256 amount, bytes holderData, bytes operatorData) public;
function burn(uint256 amount, bytes holderData) public;
function operatorBurn(address from, uint256 amount, bytes holderData, bytes operatorData) public;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes holderData,
bytes operatorData
); // solhint-disable-next-line separate-by-one-line-in-contract
event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes holderData, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// solhint-disable-next-line compiler-fixed
interface ERC777TokensSender {
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// solhint-disable-next-line compiler-fixed
interface ERC777TokensRecipient {
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
contract ERC777BaseToken is ERC777Token, ERC820Implementer {
using SafeMath for uint256;
string internal mName;
string internal mSymbol;
uint256 internal mGranularity;
uint256 internal mTotalSupply;
mapping(address => uint) internal mBalances;
mapping(address => mapping(address => bool)) internal mAuthorized;
address[] internal mDefaultOperators;
mapping(address => bool) internal mIsDefaultOperator;
mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator;
/* -- Constructor -- */
//
/// @notice Constructor to create a ReferenceToken
/// @param _name Name of the new token
/// @param _symbol Symbol of the new token.
/// @param _granularity Minimum transferable chunk.
function ERC777BaseToken(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal {
mName = _name;
mSymbol = _symbol;
mTotalSupply = 0;
require(_granularity >= 1);
mGranularity = _granularity;
mDefaultOperators = _defaultOperators;
for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; }
setInterfaceImplementation("ERC777Token", this);
}
/* -- ERC777 Interface Implementation -- */
//
/// @return the name of the token
function name() public constant returns (string) { return mName; }
/// @return the symbol of the token
function symbol() public constant returns (string) { return mSymbol; }
/// @return the granularity of the token
function granularity() public constant returns (uint256) { return mGranularity; }
/// @return the total supply of the token
function totalSupply() public constant returns (uint256) { return mTotalSupply; }
/// @notice Return the account balance of some account
/// @param _tokenHolder Address for which the balance is returned
/// @return the balance of `_tokenAddress`.
function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; }
/// @notice Return the list of default operators
/// @return the list of all the default operators
function defaultOperators() public view returns (address[]) { return mDefaultOperators; }
/// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
function send(address _to, uint256 _amount, bytes _userData) public {
doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true);
}
/// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens.
/// @param _operator The operator that wants to be Authorized
function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][msg.sender] = false;
} else {
mAuthorized[_operator][msg.sender] = true;
}
AuthorizedOperator(_operator, msg.sender);
}
/// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens.
/// @param _operator The operator that wants to be Revoked
function revokeOperator(address _operator) public {
require(_operator != msg.sender);
if (mIsDefaultOperator[_operator]) {
mRevokedDefaultOperator[_operator][msg.sender] = true;
} else {
mAuthorized[_operator][msg.sender] = false;
}
RevokedOperator(_operator, msg.sender);
}
/// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address.
/// @param _operator address to check if it has the right to manage the tokens
/// @param _tokenHolder address which holds the tokens to be managed
/// @return `true` if `_operator` is authorized for `_tokenHolder`
function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) {
return (_operator == _tokenHolder
|| mAuthorized[_operator][_tokenHolder]
|| (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]));
}
/// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`.
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
/// @param _userData Data generated by the user to be sent to the recipient
/// @param _operatorData Data generated by the operator to be sent to the recipient
function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _from));
doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true);
}
function burn(uint256 _amount, bytes _holderData) public {
doBurn(msg.sender, msg.sender, _amount, _holderData, "");
}
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _tokenHolder));
doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData);
}
/* -- Helper Functions -- */
//
/// @notice Internal function that ensures `_amount` is multiple of the granularity
/// @param _amount The quantity that want's to be checked
function requireMultiple(uint256 _amount) internal view {
require(_amount.div(mGranularity).mul(mGranularity) == _amount);
}
/// @notice Check whether an address is a regular address or not.
/// @param _addr Address of the contract that has to be checked
/// @return `true` if `_addr` is a regular address (not a contract)
function isRegularAddress(address _addr) internal constant returns(bool) {
if (_addr == 0) { return false; }
uint size;
assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly
return size == 0;
}
/// @notice Helper function actually performing the sending of tokens.
/// @param _operator The address performing the send
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
/// @param _userData Data generated by the user to be passed to the recipient
/// @param _operatorData Data generated by the operator to be passed to the recipient
/// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
/// implementing `erc777_tokenHolder`.
/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
/// functions SHOULD set this parameter to `false`.
function doSend(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
)
internal
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _userData, _operatorData);
require(_to != address(0)); // forbid sending to 0x0 (=burning)
require(mBalances[_from] >= _amount); // ensure enough funds
mBalances[_from] = mBalances[_from].sub(_amount);
mBalances[_to] = mBalances[_to].add(_amount);
callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
Sent(_operator, _from, _to, _amount, _userData, _operatorData);
}
/// @notice Helper function actually performing the burning of tokens.
/// @param _operator The address performing the burn
/// @param _tokenHolder The address holding the tokens being burn
/// @param _amount The number of tokens to be burnt
/// @param _holderData Data generated by the token holder
/// @param _operatorData Data generated by the operator
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData)
internal
{
requireMultiple(_amount);
require(balanceOf(_tokenHolder) >= _amount);
mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount);
mTotalSupply = mTotalSupply.sub(_amount);
callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData);
Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData);
}
/// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it.
/// May throw according to `_preventLocking`
/// @param _operator The address performing the send or mint
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
/// @param _userData Data generated by the user to be passed to the recipient
/// @param _operatorData Data generated by the operator to be passed to the recipient
/// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
/// implementing `ERC777TokensRecipient`.
/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
/// functions SHOULD set this parameter to `false`.
function callRecipient(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
)
internal
{
address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient");
if (recipientImplementation != 0) {
ERC777TokensRecipient(recipientImplementation).tokensReceived(
_operator, _from, _to, _amount, _userData, _operatorData);
} else if (_preventLocking) {
require(isRegularAddress(_to));
}
}
/// @notice Helper function that checks for ERC777TokensSender on the sender and calls it.
/// May throw according to `_preventLocking`
/// @param _from The address holding the tokens being sent
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be sent
/// @param _userData Data generated by the user to be passed to the recipient
/// @param _operatorData Data generated by the operator to be passed to the recipient
/// implementing `ERC777TokensSender`.
/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
/// functions SHOULD set this parameter to `false`.
function callSender(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData
)
internal
{
address senderImplementation = interfaceAddr(_from, "ERC777TokensSender");
if (senderImplementation == 0) { return; }
ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData);
}
}
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken {
bool internal mErc20compatible;
bool public unlocked;
mapping(address => mapping(address => bool)) internal mAuthorized;
mapping(address => mapping(address => uint256)) internal mAllowed;
function ERC777ERC20BaseToken(
string _name,
string _symbol,
uint256 _granularity,
address[] _defaultOperators
)
internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators)
{
mErc20compatible = true;
unlocked = true;
setInterfaceImplementation("ERC20Token", this);
}
/// @notice This modifier is applied to erc20 obsolete methods that are
/// implemented only to maintain backwards compatibility. When the erc20
/// compatibility is disabled, this methods will fail.
modifier erc20 () {
require(mErc20compatible);
_;
}
/// @notice For Backwards compatibility
/// @return The decimls of the token. Forced to 18 in ERC777.
function decimals() public erc20 constant returns (uint8) { return uint8(18); }
/// @notice ERC20 backwards compatible transfer.
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be transferred
/// @return `true`, if the transfer can't be done, it should fail.
function transfer(address _to, uint256 _amount) public erc20 returns (bool success) {
doSend(msg.sender, msg.sender, _to, _amount, "", "", false);
return true;
}
/// @notice ERC20 backwards compatible transferFrom.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be transferred
/// @return `true`, if the transfer can't be done, it should fail.
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) {
require(_amount <= mAllowed[_from][msg.sender]);
// Cannot be after doSend because of tokensReceived re-entry
mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount);
doSend(msg.sender, _from, _to, _amount, "", "", false);
return true;
}
/// @notice ERC20 backwards compatible approve.
/// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf.
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The number of tokens to be approved for transfer
/// @return `true`, if the approve can't be done, it should fail.
function approve(address _spender, uint256 _amount) public erc20 returns (bool success) {
mAllowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @notice ERC20 backwards compatible allowance.
/// This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) {
return mAllowed[_owner][_spender];
}
function doSend(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
)
internal
{
require(unlocked);
super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
if (mErc20compatible) { Transfer(_from, _to, _amount); }
}
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData)
internal
{
super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData);
if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); }
}
}
contract ReferenceToken is ERC777ERC20BaseToken, Ownable {
address private mBurnOperator;
function ReferenceToken(
string _name,
string _symbol,
uint256 _granularity,
address[] _defaultOperators,
address _burnOperator
) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) {
mBurnOperator = _burnOperator;
}
/// @notice Disables the ERC20 interface. This function can only be called
/// by the owner.
function disableERC20() public onlyOwner {
mErc20compatible = false;
setInterfaceImplementation("ERC20Token", 0x0);
}
/// @notice Re enables the ERC20 interface. This function can only be called
/// by the owner.
function enableERC20() public onlyOwner {
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
}
/// @notice Disables an interface. This function can only be called
/// by the owner.
function disableInterface(string _interface) public onlyOwner { setInterfaceImplementation(_interface, 0x0); }
/// @notice Enables an interface. This function can only be called
/// by the owner.
function enableInterface(string _interface, address _impl) public onlyOwner { setInterfaceImplementation(_interface, _impl); }
/// @notice sets the manager of register implementations of interfaces. This function can only be called
/// by the owner.
function delegateERC820Management(address _newManager) public onlyOwner { delegateManagement(_newManager); }
/// @notice Locks the token. In later stage, this feature will be disabled. This function can only be called
/// by the owner.
function lock() public onlyOwner { unlocked = false; }
/// @notice Unlocks the token. This function can only be called
/// by the owner.
function unlock() public onlyOwner { unlocked = true;}
/* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */
//
/// @notice Generates `_amount` tokens to be assigned to `_tokenHolder`
/// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient.
/// @param _tokenHolder The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @param _operatorData Data that will be passed to the recipient as a first transfer
function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner {
requireMultiple(_amount);
mTotalSupply = mTotalSupply.add(_amount);
mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount);
callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true);
Minted(msg.sender, _tokenHolder, _amount, _operatorData);
if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); }
}
/// @notice Burns `_amount` tokens from `_tokenHolder`
/// Silly example of overriding the `burn` function to only let the owner burn its tokens.
/// Do not forget to override the `burn` function in your token contract if you want to prevent users from
/// burning their tokens.
/// @param _amount The quantity of tokens to burn
function burn(uint256 _amount, bytes _holderData) public onlyOwner {
require(msg.sender == mBurnOperator);
super.burn(_amount, _holderData);
}
/// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator`
/// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens.
/// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from
/// burning their tokens.
/// @param _tokenHolder The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public {
require(msg.sender == mBurnOperator);
super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData);
}
} | Re enables the ERC20 interface. This function can only be called by the owner. | function enableERC20() public onlyOwner {
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
}
| 2,445,238 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSA.sol";
import "../utils/cryptography/draft-EIP712.sol";
import "../utils/introspection/ERC165.sol";
import "../utils/math/SafeCast.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/Timers.sol";
import "./IGovernor.sol";
/**
* @dev Core of the governance system, designed to be extended though various modules.
*
* This contract is abstract and requires several function to be implemented in various modules:
*
* - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
/**
* @dev Restrict access to governor executing address. Some module might override the _executor function to make
* sure this modifier is consistant with the execution model.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore memory proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
} else if (proposal.canceled) {
return ProposalState.Canceled;
} else if (proposal.voteStart.isPending()) {
return ProposalState.Pending;
} else if (proposal.voteEnd.isPending()) {
return ProposalState.Active;
} else if (proposal.voteEnd.isExpired()) {
return
_quorumReached(proposalId) && _voteSucceeded(proposalId)
? ProposalState.Succeeded
: ProposalState.Defeated;
} else {
revert("Governor: unknown proposal id");
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual;
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
_countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165.sol";
/**
* @dev Interface of the {Governor} core.
*
* _Available since v4.3._
*/
abstract contract IGovernor is IERC165 {
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/
function name() public view virtual returns (string memory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/
function version() public view virtual returns (string memory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual returns (string memory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/
function hashProposal(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata calldatas,
bytes32 descriptionHash
) public pure virtual returns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId) public view virtual returns (ProposalState);
/**
* @notice module:core
* @dev block number used to retrieve user's votes and quorum.
*/
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:core
* @dev timestamp at which votes close.
*/
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/
function votingDelay() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of blocks, between the vote start and vote ends.
*
* Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/
function votingPeriod() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
/**
* @dev Cast a with a reason
*
* Emits a {VoteCast} event.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 balance);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/AccessControl.sol";
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`.
*/
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
require(isOperationReady(id), "TimelockController: operation is not ready");
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(
bytes32 id,
uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IGovernor.sol";
/**
* @dev Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility.
*
* _Available since v4.3._
*/
abstract contract IGovernorCompatibilityBravo is IGovernor {
/**
* @dev Proposal structure from Compound Governor Bravo. Not actually used by the compatibility layer, as
* {{proposal}} returns a very different structure.
*/
struct Proposal {
uint256 id;
address proposer;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool executed;
mapping(address => Receipt) receipts;
}
/**
* @dev Receipt structure from Compound Governor Bravo
*/
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
/**
* @dev Part of the Governor Bravo's interface.
*/
function quorumVotes() public view virtual returns (uint256);
/**
* @dev Part of the Governor Bravo's interface: _"The official record of all proposals ever proposed"_.
*/
function proposals(uint256)
public
view
virtual
returns (
uint256 id,
address proposer,
uint256 eta,
uint256 startBlock,
uint256 endBlock,
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes,
bool canceled,
bool executed
);
/**
* @dev Part of the Governor Bravo's interface: _"Function used to propose a new proposal"_.
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256);
/**
* @dev Part of the Governor Bravo's interface: _"Queues a proposal of state succeeded"_.
*/
function queue(uint256 proposalId) public virtual;
/**
* @dev Part of the Governor Bravo's interface: _"Executes a queued proposal if eta has passed"_.
*/
function execute(uint256 proposalId) public payable virtual;
/**
* @dev Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
*/
function cancel(uint256 proposalId) public virtual;
/**
* @dev Part of the Governor Bravo's interface: _"Gets actions of a proposal"_.
*/
function getActions(uint256 proposalId)
public
view
virtual
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
);
/**
* @dev Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_.
*/
function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory);
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Governor.sol";
/**
* @dev Extension of {Governor} for proposal restriction to token holders with a minimum balance.
*
* _Available since v4.3._
*/
abstract contract GovernorProposalThreshold is Governor {
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IGovernorTimelock.sol";
import "../Governor.sol";
import "../TimelockController.sol";
/**
* @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a
* delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The
* {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly.
*
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
* inaccessible.
*
* _Available since v4.3._
*/
abstract contract GovernorTimelockControl is IGovernorTimelock, Governor {
TimelockController private _timelock;
mapping(uint256 => bytes32) private _timelockIds;
/**
* @dev Emitted when the timelock controller used for proposal execution is modified.
*/
event TimelockChange(address oldTimelock, address newTimelock);
/**
* @dev Set the timelock.
*/
constructor(TimelockController timelockAddress) {
_updateTimelock(timelockAddress);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Overriden version of the {Governor-state} function with added support for the `Queued` status.
*/
function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
ProposalState status = super.state(proposalId);
if (status != ProposalState.Succeeded) {
return status;
}
// core tracks execution, so we just have to check if successful proposal have been queued.
bytes32 queueid = _timelockIds[proposalId];
if (queueid == bytes32(0)) {
return status;
} else if (_timelock.isOperationDone(queueid)) {
return ProposalState.Executed;
} else {
return ProposalState.Queued;
}
}
/**
* @dev Public accessor to check the address of the timelock
*/
function timelock() public view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Public accessor to check the eta of a queued proposal
*/
function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]);
return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
}
/**
* @dev Function to queue a proposal to the timelock.
*/
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");
uint256 delay = _timelock.getMinDelay();
_timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);
_timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay);
emit ProposalQueued(proposalId, block.timestamp + delay);
return proposalId;
}
/**
* @dev Overriden execute function that run the already queued proposal through the timelock.
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override {
_timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
}
/**
* @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
* been queued.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override returns (uint256) {
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
if (_timelockIds[proposalId] != 0) {
_timelock.cancel(_timelockIds[proposalId]);
delete _timelockIds[proposalId];
}
return proposalId;
}
/**
* @dev Address through which the governor executes action. In this case, the timelock.
*/
function _executor() internal view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
* must be proposed, scheduled and executed using the {Governor} workflow.
*/
function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance {
_updateTimelock(newTimelock);
}
function _updateTimelock(TimelockController newTimelock) private {
emit TimelockChange(address(_timelock), address(newTimelock));
_timelock = newTimelock;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Governor.sol";
import "../../token/ERC20/extensions/ERC20Votes.sol";
import "../../utils/math/Math.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token.
*
* _Available since v4.3._
*/
abstract contract GovernorVotes is Governor {
ERC20Votes public immutable token;
constructor(ERC20Votes tokenAddress) {
token = tokenAddress;
}
/**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return token.getPastVotes(account, blockNumber);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IGovernor.sol";
/**
* @dev Extension of the {IGovernor} for timelock supporting modules.
*
* _Available since v4.3._
*/
abstract contract IGovernorTimelock is IGovernor {
event ProposalQueued(uint256 proposalId, uint256 eta);
function timelock() public view virtual returns (address);
function proposalEta(uint256 proposalId) public view virtual returns (uint256);
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual returns (uint256 proposalId);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
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 "./draft-ERC20Permit.sol";
import "../../../utils/math/Math.sol";
import "../../../utils/math/SafeCast.sol";
import "../../../utils/cryptography/ECDSA.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
return _delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Tooling for timepoints, timers and delays
*/
library Timers {
struct Timestamp {
uint64 _deadline;
}
function getDeadline(Timestamp memory timer) internal pure returns (uint64) {
return timer._deadline;
}
function setDeadline(Timestamp storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(Timestamp storage timer) internal {
timer._deadline = 0;
}
function isUnset(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(Timestamp memory timer) internal view returns (bool) {
return timer._deadline > block.timestamp;
}
function isExpired(Timestamp memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.timestamp;
}
struct BlockNumber {
uint64 _deadline;
}
function getDeadline(BlockNumber memory timer) internal pure returns (uint64) {
return timer._deadline;
}
function setDeadline(BlockNumber storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(BlockNumber storage timer) internal {
timer._deadline = 0;
}
function isUnset(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(BlockNumber memory timer) internal view returns (bool) {
return timer._deadline > block.number;
}
function isExpired(BlockNumber memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.number;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/governance/extensions/IGovernorTimelock.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorProposalThreshold.sol";
import "@openzeppelin/contracts/governance/Governor.sol";
import "@openzeppelin/contracts/governance/compatibility/IGovernorCompatibilityBravo.sol";
/**
* @dev Compatibility layer that implements GovernorBravo compatibility on to of {Governor}.
*
* This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added
* through inheritance. It does not include token bindings, not does it include any variable upgrade patterns.
*
* _Available since v4.3._
*/
abstract contract GovernorCompatibilityBravoWithVeto is
IGovernorTimelock,
IGovernorCompatibilityBravo,
Governor,
GovernorProposalThreshold
{
using Counters for Counters.Counter;
using Timers for Timers.BlockNumber;
event VetoerSet(address newVetoer);
enum VoteType {
Against,
For,
Abstain
}
struct ProposalDetails {
address proposer;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
mapping(address => Receipt) receipts;
bytes32 descriptionHash;
}
mapping(uint256 => ProposalDetails) private _proposalDetails;
address public vetoer;
constructor(address initialVetoer) {
vetoer = initialVetoer;
emit VetoerSet(initialVetoer);
}
function setVetoer(address newVetoer) external {
require(msg.sender == vetoer, "NOT_AUTHORIZED");
vetoer = newVetoer;
emit VetoerSet(vetoer);
}
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual override returns (string memory) {
return "support=bravo&quorum=bravo";
}
// ============================================== Proposal lifecycle ==============================================
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override(IGovernor, Governor, GovernorProposalThreshold) returns (uint256) {
_storeProposal(_msgSender(), targets, values, new string[](calldatas.length), calldatas, description);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev See {IGovernorCompatibilityBravo-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
_storeProposal(_msgSender(), targets, values, signatures, calldatas, description);
return propose(targets, values, _encodeCalldata(signatures, calldatas), description);
}
/**
* @dev See {IGovernorCompatibilityBravo-queue}.
*/
function queue(uint256 proposalId) public virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
queue(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
/**
* @dev See {IGovernorCompatibilityBravo-execute}.
*/
function execute(uint256 proposalId) public payable virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
execute(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
function cancel(uint256 proposalId) public virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
require(
_msgSender() == details.proposer || getVotes(details.proposer, block.number - 1) < proposalThreshold(),
"GovernorBravo: proposer above threshold"
);
_cancel(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
function veto(uint256 proposalId) external virtual {
ProposalDetails storage details = _proposalDetails[proposalId];
require(_msgSender() == vetoer, "GovernorBravo: not vetoer");
_cancel(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
/**
* @dev Encodes calldatas with optional function signature.
*/
function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas)
private
pure
returns (bytes[] memory)
{
bytes[] memory fullcalldatas = new bytes[](calldatas.length);
for (uint256 i = 0; i < signatures.length; ++i) {
fullcalldatas[i] = bytes(signatures[i]).length == 0
? calldatas[i]
: abi.encodeWithSignature(signatures[i], calldatas[i]);
}
return fullcalldatas;
}
/**
* @dev Store proposal metadata for later lookup
*/
function _storeProposal(
address proposer,
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) private {
bytes32 descriptionHash = keccak256(bytes(description));
uint256 proposalId = hashProposal(targets, values, _encodeCalldata(signatures, calldatas), descriptionHash);
ProposalDetails storage details = _proposalDetails[proposalId];
if (details.descriptionHash == bytes32(0)) {
details.proposer = proposer;
details.targets = targets;
details.values = values;
details.signatures = signatures;
details.calldatas = calldatas;
details.descriptionHash = descriptionHash;
}
}
// ==================================================== Views =====================================================
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold()
public
view
virtual
override(IGovernorCompatibilityBravo, GovernorProposalThreshold)
returns (uint256);
/**
* @dev See {IGovernorCompatibilityBravo-proposals}.
*/
function proposals(uint256 proposalId)
public
view
virtual
override
returns (
uint256 id,
address proposer,
uint256 eta,
uint256 startBlock,
uint256 endBlock,
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes,
bool canceled,
bool executed
)
{
id = proposalId;
eta = proposalEta(proposalId);
startBlock = proposalSnapshot(proposalId);
endBlock = proposalDeadline(proposalId);
ProposalDetails storage details = _proposalDetails[proposalId];
proposer = details.proposer;
forVotes = details.forVotes;
againstVotes = details.againstVotes;
abstainVotes = details.abstainVotes;
ProposalState status = state(proposalId);
canceled = status == ProposalState.Canceled;
executed = status == ProposalState.Executed;
}
/**
* @dev See {IGovernorCompatibilityBravo-getActions}.
*/
function getActions(uint256 proposalId)
public
view
virtual
override
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
ProposalDetails storage details = _proposalDetails[proposalId];
return (details.targets, details.values, details.signatures, details.calldatas);
}
/**
* @dev See {IGovernorCompatibilityBravo-getReceipt}.
*/
function getReceipt(uint256 proposalId, address voter) public view virtual override returns (Receipt memory) {
return _proposalDetails[proposalId].receipts[voter];
}
/**
* @dev See {IGovernorCompatibilityBravo-quorumVotes}.
*/
function quorumVotes() public view virtual override returns (uint256) {
return quorum(block.number - 1);
}
// ==================================================== Voting ====================================================
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
return _proposalDetails[proposalId].receipts[account].hasVoted;
}
/**
* @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum.
*/
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
ProposalDetails storage details = _proposalDetails[proposalId];
return quorum(proposalSnapshot(proposalId)) < details.forVotes;
}
/**
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
ProposalDetails storage details = _proposalDetails[proposalId];
return details.forVotes > details.againstVotes;
}
/**
* @dev See {Governor-_countVote}. In this module, the support follows Governor Bravo.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
Receipt storage receipt = details.receipts[account];
require(!receipt.hasVoted, "GovernorCompatibilityBravo: vote already cast");
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = SafeCast.toUint96(weight);
if (support == uint8(VoteType.Against)) {
details.againstVotes += weight;
} else if (support == uint8(VoteType.For)) {
details.forVotes += weight;
} else if (support == uint8(VoteType.Abstain)) {
details.abstainVotes += weight;
} else {
revert("GovernorCompatibilityBravo: invalid vote type");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/governance/Governor.sol";
import "../base/GovernorCompatibilityBravoWithVeto.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol";
contract BleepsDAOGovernor is Governor, GovernorCompatibilityBravoWithVeto, GovernorVotes, GovernorTimelockControl {
uint64 constant MIN_VOTING_DELAY = 1;
uint64 constant MAX_VOTING_DELAY = 45818; // 1 week;
uint64 constant MIN_VOTING_PERIOD = 19635; // 3 day;
uint64 constant MAX_VOTING_PERIOD = 91636; // 2 weeks
uint64 constant MIN_QUORUM = 16;
uint64 constant MAX_QUORUM = 128;
uint64 constant MIN_PROPOSAL_THRESHOLD = 1;
uint64 constant MAX_PROPOSAL_THRESHOLD = 64;
struct Config {
uint64 votingDelay;
uint64 votingPeriod;
uint64 quorum;
uint64 proposalThreshold;
}
Config internal _config;
constructor(
ERC20Votes _token,
TimelockController _timelock,
address initialVetoer
)
Governor("BleepsDAOGovernor")
GovernorCompatibilityBravoWithVeto(initialVetoer)
GovernorVotes(_token)
GovernorTimelockControl(_timelock)
{
uint64 initialVotingDelay = 1;
uint64 initialVotingPeriod = 45818; // 1 week
uint64 initialQuorum = 64; // 64 / 576 = 11.111.. % if new Bleeps are minted (max supply = 1024), this should be updated
uint64 initialProposalThreshold = 1;
_setConfig(initialVotingDelay, initialVotingPeriod, initialQuorum, initialProposalThreshold);
}
function votingDelay() public view override returns (uint256) {
return _config.votingDelay;
}
function votingPeriod() public view override returns (uint256) {
return _config.votingPeriod;
}
function quorum(uint256) public view override returns (uint256) {
return _config.quorum;
}
function proposalThreshold() public view override returns (uint256) {
return _config.proposalThreshold;
}
function setConfig(
uint64 newVotingDelay,
uint64 newVotingPeriod,
uint64 newQuorum,
uint64 newProposalThreshold
) external onlyGovernance {
_setConfig(newVotingDelay, newVotingPeriod, newQuorum, newProposalThreshold);
}
function _setConfig(
uint64 newVotingDelay,
uint64 newVotingPeriod,
uint64 newQuorum,
uint64 newProposalThreshold
) internal {
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "INVALID_VOTING_DELAY");
_config.votingDelay = newVotingDelay;
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "INVALID_VOTING_PERIOD");
_config.votingPeriod = newVotingPeriod;
require(newQuorum >= MIN_QUORUM && newQuorum <= MAX_QUORUM, "INVALID_QUORUM");
_config.quorum = newQuorum;
require(
newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD,
"INVALID_PROPOSAL_THRESHOLD"
);
_config.proposalThreshold = newProposalThreshold;
}
// The following functions are overrides required by Solidity.
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernor, GovernorVotes)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function state(uint256 proposalId)
public
view
override(Governor, IGovernor, GovernorTimelockControl)
returns (ProposalState)
{
return super.state(proposalId);
}
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public override(Governor, GovernorCompatibilityBravoWithVeto, IGovernor) returns (uint256) {
return super.propose(targets, values, calldatas, description);
}
function _execute(
uint256 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal override(Governor, GovernorTimelockControl) {
super._execute(proposalId, targets, values, calldatas, descriptionHash);
}
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal override(Governor, GovernorTimelockControl) returns (uint256) {
return super._cancel(targets, values, calldatas, descriptionHash);
}
function _executor() internal view override(Governor, GovernorTimelockControl) returns (address) {
return super._executor();
}
function supportsInterface(bytes4 interfaceId)
public
view
override(Governor, IERC165, GovernorTimelockControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
} | Emitted when the timelock controller used for proposal execution is modified./ Set the timelock./ | function proposalThreshold() public view virtual returns (uint256);
}
pragma solidity ^0.8.0;
import "./IGovernorTimelock.sol";
import "../Governor.sol";
import "../TimelockController.sol";
constructor(TimelockController timelockAddress) {
_updateTimelock(timelockAddress);
}
| 5,730,254 |
// SPDX-License-Identifier: MIT
import "https://github.com/smartcontractkit/chainlink/blob/0964ca290565587963cc4ad8f770274f5e0d9e9d/evm-contracts/src/v0.6/VRFConsumerBase.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/utils/ReentrancyGuard.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/token/ERC20/SafeERC20.sol";
pragma solidity 0.6.12;
// PolyrollERC20 is the contract that governs the 3 games at Polyroll.org - coin flip, dice roll, and polyroll - using ERC20 tokens
contract PolyrollERC20 is VRFConsumerBase, Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Chainlink VRF related parameters
address public constant LINK_TOKEN = 0xb0897686c545045aFc77CF20eC7A532E3120E0F1;
address public constant VRF_COORDINATOR = 0x3d2341ADb2D31f1c5530cDC622016af293177AE0;
bytes32 public constant KEY_HASH = 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da;
uint public chainlinkFee = 100000000000000; // 0.0001 LINK
// Token to be used in this game contract
address public constant GAME_TOKEN = 0xC68e83a305b0FaD69E264A1769a0A070F190D2d6;
// Each bet is deducted 0.1% or 10 basis points in favor of the house
uint public houseEdgeBP = 10;
// Modulo is the number of equiprobable outcomes in a game:
// 2 for coin flip
// 6 for dice roll
// 6*6 = 36 for double dice
// 37 for roulette
// 100 for polyroll
uint constant MAX_MODULO = 100;
// Modulos below MAX_MASK_MODULO are checked against a bit mask, allowing betting on specific outcomes.
// For example in a dice roll (modolo = 6),
// 000001 mask means betting on 1. 000001 converted from binary to decimal becomes 1.
// 101000 mask means betting on 4 and 6. 101000 converted from binary to decimal becomes 40.
// The specific value is dictated by the fact that 256-bit intermediate
// multiplication result allows implementing population count efficiently
// for numbers that are up to 42 bits, and 40 is the highest multiple of
// eight below 42.
uint constant MAX_MASK_MODULO = 40;
// This is a check on bet mask overflow. Maximum mask is equivalent to number of possible binary outcomes for maximum modulo.
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
// These are constants taht make O(1) population count in placeBet possible.
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
// In addition to house edge, wealth tax is added every time the bet amount exceeds a multiple of a threshold.
// For example, if wealthTaxIncrementThreshold = 10000 ether,
// A bet amount of 10000 ether will have a wealth tax of 0.01% in addition to house edge.
// A bet amount of 20000 ether will have a wealth tax of 0.02% in addition to house edge.
uint public wealthTaxThreshold = 2000 ether;
uint public wealthTaxBP = 0;
// minimum and maximum bets.
uint public minBetAmount = 50 ether;
uint public maxBetAmount = 5000 ether;
// max bet profit. Used to cap bets against dynamic odds. Usually set to 20 x maxBetAmount.
uint public maxProfit = 20 * 5000 ether;
// Funds that are locked in potentially winning bets. Prevents contract from committing to new bets that it cannot pay out.
uint public lockedInBets;
// Sum of win and loss amounts (by gamblers). Used for tracking house profits earned by contract.
uint public sumWinAmount;
uint public sumLossAmount;
// Number of open bets currently
uint public openBetCount;
// Info of each bet.
struct Bet {
// Wager amount in wei.
uint amount;
// Modulo of a game.
uint8 modulo;
// Number of winning outcomes, used to compute winning payment (* modulo/rollUnder),
// and used instead of mask for games with modulo > MAX_MASK_MODULO.
uint8 rollUnder;
// Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment).
uint40 mask;
// Block number of placeBet tx.
uint placeBlockNumber;
// Address of a gambler, used to pay out winning bets.
address gambler;
// Status of bet settlement.
bool isSettled;
// Outcome of bet.
uint outcome;
// Win amount.
uint winAmount;
// Random number used to settle bet.
uint randomNumber;
}
// List of bets
Bet[] public bets;
// Store Number of bets
uint public betsLength;
// Mapping requestId returned by Chainlink VRF to bet Id
mapping(bytes32 => uint) public betMap;
// Events
event BetPlaced(uint indexed betId, address indexed gambler);
event BetSettled(uint indexed betId, address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask, uint outcome, uint winAmount);
event BetRefunded(uint indexed betId, address indexed gambler);
// Constructor. Using Chainlink VRFConsumerBase constructor.
constructor() VRFConsumerBase(VRF_COORDINATOR, LINK_TOKEN) public {}
// See game token balance.
function balance() external view returns (uint) {
return IERC20(GAME_TOKEN).balanceOf(address(this));
}
// Update Chainlink fee
function setChainlinkFee(uint _chainlinkFee) external onlyOwner {
chainlinkFee = _chainlinkFee;
}
// Update house edge basis points
function setHouseEdgeBP(uint _houseEdgeBP) external onlyOwner {
houseEdgeBP = _houseEdgeBP;
}
// Set min bet amount. minBetAmount should be large enough such that its house edge fee can cover the Chainlink oracle fee.
function setMinBetAmount(uint _minBetAmount) external onlyOwner {
minBetAmount = _minBetAmount;
}
// Set max bet amount.
function setMaxBetAmount(uint _maxBetAmount) external onlyOwner {
maxBetAmount = _maxBetAmount;
}
// Set max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) external onlyOwner {
maxProfit = _maxProfit;
}
// Set wealth tax BP to be added to house edge percent. Setting this to zero effectively disables wealth tax.
function setWealthTaxBP(uint _wealthTaxBP) external onlyOwner {
wealthTaxBP = _wealthTaxBP;
}
// Set threshold to trigger wealth tax.
function setWealthTaxThreshold(uint _wealthTaxThreshold) external onlyOwner {
wealthTaxThreshold = _wealthTaxThreshold;
}
// Withdraw funds not exceeding balance minus potential win prizes by open bets
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)), "Withdrawal amount larger than balance.");
require (withdrawAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)) - lockedInBets, "Withdrawal amount larger than balance minus lockedInBets");
IERC20(GAME_TOKEN).safeTransfer(beneficiary, withdrawAmount);
}
// Withdraw LINK tokens only
function withdrawLink() external onlyOwner {
IERC20(LINK_TOKEN).safeTransfer(owner(), IERC20(LINK_TOKEN).balanceOf(address(this)));
}
// Place bet
function placeBet(uint256 amount, uint betMask, uint modulo) external nonReentrant {
// Validate input data.
require(LINK.balanceOf(address(this)) >= chainlinkFee, "Not enough LINK in contract.");
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= minBetAmount && amount <= maxBetAmount, "Bet amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
// Transfer game token to contract
IERC20(GAME_TOKEN).safeTransferFrom(address(msg.sender), address(this), amount);
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
// Small modulo games can specify exact bet outcomes via bit mask.
// rollUnder is a number of 1 bits in this mask (population count).
// This magic looking formula is an efficient way to compute population
// count on EVM for numbers below 2**40.
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
// Larger modulos games specify the right edge of half-open interval of winning bet outcomes.
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
// Winning amount.
uint possibleWinAmount = getDiceWinAmount(amount, modulo, rollUnder);
// Enforce max profit limit. Bet will not be placed if condition is not met.
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
// Check whether contract has enough funds to accept this bet.
require (lockedInBets + possibleWinAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)), "Unable to accept bet due to insufficient funds");
// Update lock funds.
lockedInBets += possibleWinAmount;
// Store bet in bet list
bets.push(Bet(
{
amount: amount,
modulo: uint8(modulo),
rollUnder: uint8(rollUnder),
mask: uint40(mask),
placeBlockNumber: block.number,
gambler: msg.sender,
isSettled: false,
outcome: 0,
winAmount: 0,
randomNumber: 0
}
));
// Request random number from Chainlink VRF. Store requestId for validation checks later.
bytes32 requestId = requestRandomness(KEY_HASH, chainlinkFee, betsLength);
// Map requestId to bet ID
betMap[requestId] = betsLength;
// Record bet in event logs
emit BetPlaced(betsLength, msg.sender);
betsLength++;
openBetCount++;
}
// Get the expected win amount after house edge is subtracted.
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private view returns (uint winAmount) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
uint houseEdge = amount * (houseEdgeBP + getWealthTax(amount)) / 10000;
winAmount = (amount - houseEdge) * modulo / rollUnder;
}
// Get wealth tax
function getWealthTax(uint amount) private view returns (uint wealthTax) {
wealthTax = amount / wealthTaxThreshold * wealthTaxBP;
}
// Callback function called by VRF coordinator
function fulfillRandomness(bytes32 requestId, uint randomness) internal override {
settleBet(requestId, randomness);
}
// Settle bet. Function can only be called by fulfillRandomness function, which in turn can only be called by Chainlink VRF.
function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant {
uint betId = betMap[requestId];
Bet storage bet = bets[betId];
uint amount = bet.amount;
// Validation check
require (amount > 0, "Bet does not exist."); // Check that bet exists
require(bet.isSettled == false, "Bet is settled already"); // Check that bet is not settled yet
// Fetch bet parameters into local variables (to save gas).
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
// Do a roll by taking a modulo of random number.
uint outcome = randomNumber % modulo;
// Win amount if gambler wins this bet
uint possibleWinAmount = getDiceWinAmount(amount, modulo, rollUnder);
// Actual win amount by gambler
uint winAmount = 0;
// Determine dice outcome.
if (modulo <= MAX_MASK_MODULO) {
// For small modulo games, check the outcome against a bit mask.
if ((2 ** outcome) & bet.mask != 0) {
winAmount = possibleWinAmount;
}
} else {
// For larger modulos, check inclusion into half-open interval.
if (outcome < rollUnder) {
winAmount = possibleWinAmount;
}
}
// Record bet settlement in event log.
emit BetSettled(betId, gambler, amount, uint8(modulo), uint8(rollUnder), bet.mask, outcome, winAmount);
// Unlock possibleWinAmount from lockedInBets, regardless of the outcome.
lockedInBets -= possibleWinAmount;
// Update bet records
bet.isSettled = true;
bet.winAmount = winAmount;
bet.randomNumber = randomNumber;
bet.outcome = outcome;
if (winAmount > 0) {
// Send win amount to gambler.
IERC20(GAME_TOKEN).safeTransfer(address(gambler), winAmount);
sumWinAmount += winAmount - amount;
} else {
sumLossAmount += amount;
}
openBetCount--;
}
// Return the bet in extremely unlikely scenario it was not settled by Chainlink VRF.
// In case you ever find yourself in a situation like this, just contact Polyroll support.
// However, nothing precludes you from calling this method yourself.
function refundBet(uint betId) external nonReentrant {
Bet storage bet = bets[betId];
uint amount = bet.amount;
// Validation check
require (amount > 0, "Bet does not exist."); // Check that bet exists
require (bet.isSettled == false, "Bet is settled already."); // Check that bet is still open
require (block.number > bet.placeBlockNumber + 43200, "Wait after placing bet before requesting refund.");
uint possibleWinAmount = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
// Unlock possibleWinAmount from lockedInBets, regardless of the outcome.
lockedInBets -= possibleWinAmount;
// Update bet records
bet.isSettled = true;
bet.winAmount = amount;
// Send the refund.
IERC20(GAME_TOKEN).safeTransfer(address(bet.gambler), amount);
// Record refund in event logs
emit BetRefunded(betId, bet.gambler);
openBetCount--;
}
} | Withdraw funds not exceeding balance minus potential win prizes by open bets | function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)), "Withdrawal amount larger than balance.");
require (withdrawAmount <= IERC20(GAME_TOKEN).balanceOf(address(this)) - lockedInBets, "Withdrawal amount larger than balance minus lockedInBets");
IERC20(GAME_TOKEN).safeTransfer(beneficiary, withdrawAmount);
}
| 12,684,082 |
./full_match/11155111/0x14cb6EDb15c156272B59e7Fd688a1F0b09C999d4/sources/src/Bridge.sol | Initializer, should be called in the same tx as deployment token_ Address of ERC20 token to manage votesRequired_ initial `votesRequired` mintDelay_ initial `votesRequired` fee_ initial `votesRequired` counterLimit initial `rateLimit.counterLimit` decayRate initial `rateLimit.decayRate` supplyLimit_ initial `supplyLimit` slither-disable-start events-maths slither-disable-end events-maths | function initialize(
WrappedToken token_,
uint32 votesRequired_,
uint256 mintDelay_,
uint256 fee_,
uint256 counterLimit,
uint256 decayRate,
uint256 supplyLimit_
) public initializer {
__AccessControl_init();
__UUPSUpgradeable_init();
token = token_;
rateLimit.counterLimit = counterLimit;
rateLimit.decayRate = decayRate;
votesRequired = votesRequired_;
fee = fee_;
mintDelay = mintDelay_;
supplyLimit = supplyLimit_;
_grantRole(SUPER_ADMIN_ROLE, msg.sender);
}
| 3,786,674 |
./full_match/137/0x86c18085B8949FF3DC53eC5c3a3a143CCFbC960a/sources/contracts/Mad_Honey/ERC721M.sol | Sets mintable./ | function setMintable(bool mintable) external onlyOwner {
_mintable = mintable;
emit SetMintable(mintable);
}
| 4,678,055 |
./full_match/1/0x02c500255762EFFF926348f1eC2e248dc8EBA10f/sources/contracts/Pool.sol | @inheritdoc ICollateralLiquidationReceiver/ Validate caller is collateral liquidator / Compute loan receipt hash / Validate loan status is liquidated / Decode loan receipt / Compute borrower's share of liquidation surplus / Compute remaining proceeds / Restore liquidity nodes / | function onCollateralLiquidated(bytes calldata encodedLoanReceipt, uint256 proceeds) external nonReentrant {
if (msg.sender != address(_collateralLiquidator)) revert InvalidCaller();
bytes32 loanReceiptHash = LoanReceipt.hash(encodedLoanReceipt);
if (_loans[loanReceiptHash] != LoanStatus.Liquidated) revert InvalidLoanReceipt();
LoanReceipt.LoanReceiptV1 memory loanReceipt = LoanReceipt.decode(encodedLoanReceipt);
uint256 borrowerSurplus = proceeds > loanReceipt.repayment
? Math.mulDiv(proceeds - loanReceipt.repayment, BORROWER_SURPLUS_SPLIT_BASIS_POINTS, BASIS_POINTS_SCALE)
: 0;
uint128 proceedsRemaining = (proceeds - borrowerSurplus).toUint128();
for (uint256 i; i < loanReceipt.nodeReceipts.length; i++) {
uint128 restored = (i == loanReceipt.nodeReceipts.length - 1)
? proceedsRemaining
: uint128(Math.min(loanReceipt.nodeReceipts[i].pending, proceedsRemaining));
_liquidity.restore(
loanReceipt.nodeReceipts[i].tick,
loanReceipt.nodeReceipts[i].used,
loanReceipt.nodeReceipts[i].pending,
restored
);
proceedsRemaining -= restored;
}
| 9,716,379 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "./../abstract/PendleYieldTokenHolderBase.sol";
import "../../interfaces/IComptroller.sol";
contract PendleCompoundYieldTokenHolder is PendleYieldTokenHolderBase {
IComptroller private immutable comptroller;
constructor(
address _governanceManager,
address _forge,
address _yieldToken,
address _rewardToken,
address _rewardManager,
address _comptroller,
uint256 _expiry
)
PendleYieldTokenHolderBase(
_governanceManager,
_forge,
_yieldToken,
_rewardToken,
_rewardManager,
_expiry
)
{
require(_comptroller != address(0), "ZERO_ADDRESS");
comptroller = IComptroller(_comptroller);
}
function redeemRewards() external override {
address[] memory cTokens = new address[](1);
address[] memory holders = new address[](1);
cTokens[0] = yieldToken;
holders[0] = address(this);
comptroller.claimComp(holders, cTokens, false, true);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../interfaces/IPendleYieldTokenHolder.sol";
import "../../periphery/WithdrawableV2.sol";
abstract contract PendleYieldTokenHolderBase is IPendleYieldTokenHolder, WithdrawableV2 {
using SafeERC20 for IERC20;
address public immutable override yieldToken;
address public immutable override forge;
address public immutable override rewardToken;
uint256 public immutable override expiry;
constructor(
address _governanceManager,
address _forge,
address _yieldToken,
address _rewardToken,
address _rewardManager,
uint256 _expiry
) PermissionsV2(_governanceManager) {
require(_yieldToken != address(0) && _rewardToken != address(0), "ZERO_ADDRESS");
yieldToken = _yieldToken;
forge = _forge;
rewardToken = _rewardToken;
expiry = _expiry;
IERC20(_yieldToken).safeApprove(_forge, type(uint256).max);
IERC20(_rewardToken).safeApprove(_rewardManager, type(uint256).max);
}
function redeemRewards() external virtual override;
// Only forge can call this function
// this will allow a spender to spend the whole balance of the specified tokens
// the spender should ideally be a contract with logic for users to withdraw out their funds.
function setUpEmergencyMode(address spender) external override {
require(msg.sender == forge, "NOT_FROM_FORGE");
IERC20(yieldToken).safeApprove(spender, type(uint256).max);
IERC20(rewardToken).safeApprove(spender, type(uint256).max);
}
// The governance address will be able to withdraw any tokens except for
// the yieldToken and the rewardToken
function _allowedToWithdraw(address _token) internal view override returns (bool allowed) {
allowed = _token != yieldToken && _token != rewardToken;
}
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
pragma abicoder v2;
interface IComptroller {
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
}
function markets(address) external view returns (Market memory);
function claimComp(
address[] memory holders,
address[] memory cTokens,
bool borrowers,
bool suppliers
) external;
function getAccountLiquidity(address account)
external
view
returns (
uint256 error,
uint256 liquidity,
uint256 shortfall
);
function getAssetsIn(address account) external view returns (address[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
interface IPendleYieldTokenHolder {
function redeemRewards() external;
function setUpEmergencyMode(address spender) external;
function yieldToken() external returns (address);
function forge() external returns (address);
function rewardToken() external returns (address);
function expiry() external returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PermissionsV2.sol";
abstract contract WithdrawableV2 is PermissionsV2 {
using SafeERC20 for IERC20;
event EtherWithdraw(uint256 amount, address sendTo);
event TokenWithdraw(IERC20 token, uint256 amount, address sendTo);
/**
* @dev Allows governance to withdraw Ether in a Pendle contract
* in case of accidental ETH transfer into the contract.
* @param amount The amount of Ether to withdraw.
* @param sendTo The recipient address.
*/
function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance {
(bool success, ) = sendTo.call{value: amount}("");
require(success, "WITHDRAW_FAILED");
emit EtherWithdraw(amount, sendTo);
}
/**
* @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle
* contract in case of accidental token transfer into the contract.
* @param token IERC20 The address of the token contract.
* @param amount The amount of IERC20 tokens to withdraw.
* @param sendTo The recipient address.
*/
function withdrawToken(
IERC20 token,
uint256 amount,
address sendTo
) external onlyGovernance {
require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED");
token.safeTransfer(sendTo, amount);
emit TokenWithdraw(token, amount, sendTo);
}
// must be overridden by the sub contracts, so we must consider explicitly
// in each and every contract which tokens are allowed to be withdrawn
function _allowedToWithdraw(address) internal view virtual returns (bool allowed);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../core/PendleGovernanceManager.sol";
import "../interfaces/IPermissionsV2.sol";
abstract contract PermissionsV2 is IPermissionsV2 {
PendleGovernanceManager public immutable override governanceManager;
address internal initializer;
constructor(address _governanceManager) {
require(_governanceManager != address(0), "ZERO_ADDRESS");
initializer = msg.sender;
governanceManager = PendleGovernanceManager(_governanceManager);
}
modifier initialized() {
require(initializer == address(0), "NOT_INITIALIZED");
_;
}
modifier onlyGovernance() {
require(msg.sender == _governance(), "ONLY_GOVERNANCE");
_;
}
function _governance() internal view returns (address) {
return governanceManager.governance();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
contract PendleGovernanceManager {
address public governance;
address public pendingGovernance;
event GovernanceClaimed(address newGovernance, address previousGovernance);
event TransferGovernancePending(address pendingGovernance);
constructor(address _governance) {
require(_governance != address(0), "ZERO_ADDRESS");
governance = _governance;
}
modifier onlyGovernance() {
require(msg.sender == governance, "ONLY_GOVERNANCE");
_;
}
/**
* @dev Allows the pendingGovernance address to finalize the change governance process.
*/
function claimGovernance() external {
require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE");
emit GovernanceClaimed(pendingGovernance, governance);
governance = pendingGovernance;
pendingGovernance = address(0);
}
/**
* @dev Allows the current governance to set the pendingGovernance address.
* @param _governance The address to transfer ownership to.
*/
function transferGovernance(address _governance) external onlyGovernance {
require(_governance != address(0), "ZERO_ADDRESS");
pendingGovernance = _governance;
emit TransferGovernancePending(pendingGovernance);
}
}
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
pragma abicoder v2;
import "../core/PendleGovernanceManager.sol";
interface IPermissionsV2 {
function governanceManager() external returns (PendleGovernanceManager);
}
| Allows governance to withdraw Ether in a Pendle contract in case of accidental ETH transfer into the contract. amount The amount of Ether to withdraw. sendTo The recipient address./ | function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance {
require(success, "WITHDRAW_FAILED");
emit EtherWithdraw(amount, sendTo);
}
| 283,663 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributorV3.sol";
import "./interface/IPriceOracle.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
import "./Controller.sol";
/**
* @title dForce's lending reward distributor Contract
* @author dForce
*/
contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 {
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice the controller
Controller public controller;
/// @notice the global Reward distribution speed
uint256 public globalDistributionSpeed;
/// @notice the Reward distribution speed of each iToken
mapping(address => uint256) public distributionSpeed;
/// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa
mapping(address => uint256) public distributionFactorMantissa;
struct DistributionState {
// Token's last updated index, stored as a mantissa
uint256 index;
// The block number the index was last updated at
uint256 block;
}
/// @notice the Reward distribution supply state of each iToken
mapping(address => DistributionState) public distributionSupplyState;
/// @notice the Reward distribution borrow state of each iToken
mapping(address => DistributionState) public distributionBorrowState;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionSupplierIndex;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionBorrowerIndex;
/// @notice the Reward distributed into each account
mapping(address => uint256) public reward;
/// @notice the Reward token address
address public rewardToken;
/// @notice whether the reward distribution is paused
bool public paused;
/// @notice the Reward distribution speed supply side of each iToken
mapping(address => uint256) public distributionSupplySpeed;
/// @notice the global Reward distribution speed for supply
uint256 public globalDistributionSupplySpeed;
/**
* @dev Throws if called by any account other than the controller.
*/
modifier onlyController() {
require(
address(controller) == msg.sender,
"onlyController: caller is not the controller"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize(Controller _controller) external initializer {
require(
address(_controller) != address(0),
"initialize: controller address should not be zero address!"
);
__Ownable_init();
controller = _controller;
paused = true;
}
/**
* @notice set reward token address
* @dev Admin function, only owner can call this
* @param _newRewardToken the address of reward token
*/
function _setRewardToken(address _newRewardToken)
external
override
onlyOwner
{
address _oldRewardToken = rewardToken;
require(
_newRewardToken != address(0) && _newRewardToken != _oldRewardToken,
"Reward token address invalid"
);
rewardToken = _newRewardToken;
emit NewRewardToken(_oldRewardToken, _newRewardToken);
}
/**
* @notice Add the iToken as receipient
* @dev Admin function, only controller can call this
* @param _iToken the iToken to add as recipient
* @param _distributionFactor the distribution factor of the recipient
*/
function _addRecipient(address _iToken, uint256 _distributionFactor)
external
override
onlyController
{
distributionFactorMantissa[_iToken] = _distributionFactor;
distributionSupplyState[_iToken] = DistributionState({
index: 0,
block: block.number
});
distributionBorrowState[_iToken] = DistributionState({
index: 0,
block: block.number
});
emit NewRecipient(_iToken, _distributionFactor);
}
/**
* @notice Pause the reward distribution
* @dev Admin function, pause will set global speed to 0 to stop the accumulation
*/
function _pause() external override onlyOwner {
// Set the global distribution speed to 0 to stop accumulation
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], 0);
_setDistributionSupplySpeed(_iTokens[i], 0);
}
_refreshGlobalDistributionSpeeds();
_setPaused(true);
}
/**
* @notice Unpause and set distribution speeds
* @dev Admin function
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external override onlyOwner {
_setPaused(false);
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Pause/Unpause the reward distribution
* @dev Admin function
* @param _paused whether to pause/unpause the distribution
*/
function _setPaused(bool _paused) internal {
paused = _paused;
emit Paused(_paused);
}
/**
* @notice Set distribution speeds
* @dev Admin function, will fail when paused
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSpeeds(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change speeds when paused");
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
function _setDistributionSpeedsInternal(
address[] memory _borrowiTokens,
uint256[] memory _borrowSpeeds,
address[] memory _supplyiTokens,
uint256[] memory _supplySpeeds
) internal {
_setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds);
_setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds);
}
/**
* @notice Set borrow distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
*/
function _setDistributionBorrowSpeeds(
address[] calldata _iTokens,
uint256[] calldata _borrowSpeeds
) external onlyOwner {
require(!paused, "Can not change borrow speeds when paused");
_setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Set supply distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSupplySpeeds(
address[] calldata _iTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change supply speeds when paused");
_setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds);
_refreshGlobalDistributionSpeeds();
}
function _refreshGlobalDistributionSpeeds() internal {
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
uint256 _borrowSpeed;
uint256 _supplySpeed;
for (uint256 i = 0; i < _len; i++) {
_borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]);
_supplySpeed = _supplySpeed.add(
distributionSupplySpeed[_iTokens[i]]
);
}
globalDistributionSpeed = _borrowSpeed;
globalDistributionSupplySpeed = _supplySpeed;
emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed);
}
function _setDistributionBorrowSpeedsInternal(
address[] memory _iTokens,
uint256[] memory _borrowSpeeds
) internal {
require(
_iTokens.length == _borrowSpeeds.length,
"Length of _iTokens and _borrowSpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]);
}
}
function _setDistributionSupplySpeedsInternal(
address[] memory _iTokens,
uint256[] memory _supplySpeeds
) internal {
require(
_iTokens.length == _supplySpeeds.length,
"Length of _iTokens and _supplySpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]);
}
}
function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update borrow state before updating new speed
_updateDistributionState(_iToken, true);
distributionSpeed[_iToken] = _borrowSpeed;
emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed);
}
function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update supply state before updating new speed
_updateDistributionState(_iToken, false);
distributionSupplySpeed[_iToken] = _supplySpeed;
emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed);
}
/**
* @notice Update the iToken's Reward distribution state
* @dev Will be called every time when the iToken's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateDistributionState(address _iToken, bool _isBorrow)
external
override
{
// Skip all updates if it is paused
if (paused) {
return;
}
_updateDistributionState(_iToken, _isBorrow);
}
function _updateDistributionState(address _iToken, bool _isBorrow)
internal
{
require(controller.hasiToken(_iToken), "Token has not been listed");
DistributionState storage state =
_isBorrow
? distributionBorrowState[_iToken]
: distributionSupplyState[_iToken];
uint256 _speed =
_isBorrow
? distributionSpeed[_iToken]
: distributionSupplySpeed[_iToken];
uint256 _blockNumber = block.number;
uint256 _deltaBlocks = _blockNumber.sub(state.block);
if (_deltaBlocks > 0 && _speed > 0) {
uint256 _totalToken =
_isBorrow
? IiToken(_iToken).totalBorrows().rdiv(
IiToken(_iToken).borrowIndex()
)
: IERC20Upgradeable(_iToken).totalSupply();
uint256 _totalDistributed = _speed.mul(_deltaBlocks);
// Reward distributed per token since last time
uint256 _distributedPerToken =
_totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0;
state.index = state.index.add(_distributedPerToken);
}
state.block = _blockNumber;
}
/**
* @notice Update the account's Reward distribution state
* @dev Will be called every time when the account's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _account The account to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external override {
_updateReward(_iToken, _account, _isBorrow);
}
function _updateReward(
address _iToken,
address _account,
bool _isBorrow
) internal {
require(_account != address(0), "Invalid account address!");
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _iTokenIndex;
uint256 _accountIndex;
uint256 _accountBalance;
if (_isBorrow) {
_iTokenIndex = distributionBorrowState[_iToken].index;
_accountIndex = distributionBorrowerIndex[_iToken][_account];
_accountBalance = IiToken(_iToken)
.borrowBalanceStored(_account)
.rdiv(IiToken(_iToken).borrowIndex());
// Update the account state to date
distributionBorrowerIndex[_iToken][_account] = _iTokenIndex;
} else {
_iTokenIndex = distributionSupplyState[_iToken].index;
_accountIndex = distributionSupplierIndex[_iToken][_account];
_accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Update the account state to date
distributionSupplierIndex[_iToken][_account] = _iTokenIndex;
}
uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex);
uint256 _amount = _accountBalance.rmul(_deltaIndex);
if (_amount > 0) {
reward[_account] = reward[_account].add(_amount);
emit RewardDistributed(_iToken, _account, _amount, _accountIndex);
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
*/
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) public override {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, false);
_updateDistributionState(_iToken, true);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], false);
_updateReward(_iToken, _holders[j], true);
}
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
* @param _isBorrow whether to update the borrow state
*/
function _updateRewards(
address[] memory _holders,
address[] memory _iTokens,
bool _isBorrow
) internal {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, _isBorrow);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], _isBorrow);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _iTokens The _iTokens to claim from
*/
function claimReward(address[] memory _holders, address[] memory _iTokens)
public
override
{
updateRewardBatch(_holders, _iTokens);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _suppliediTokens The _suppliediTokens to claim from
* @param _borrowediTokens The _borrowediTokens to claim from
*/
function claimRewards(
address[] memory _holders,
address[] memory _suppliediTokens,
address[] memory _borrowediTokens
) external override {
_updateRewards(_holders, _suppliediTokens, false);
_updateRewards(_holders, _borrowediTokens, true);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in all iTokens by the holders
* @param _holders The account to claim for
*/
function claimAllReward(address[] memory _holders) external override {
claimReward(_holders, controller.getAlliTokens());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IInterestRateModelInterface.sol";
import "./IControllerInterface.sol";
interface IiToken {
function isSupported() external returns (bool);
function isiToken() external returns (bool);
//----------------------------------
//********* User Interface *********
//----------------------------------
function mint(address recipient, uint256 mintAmount) external;
function mintAndEnterMarket(address recipient, uint256 mintAmount) external;
function redeem(address from, uint256 redeemTokens) external;
function redeemUnderlying(address from, uint256 redeemAmount) external;
function borrow(uint256 borrowAmount) external;
function repayBorrow(uint256 repayAmount) external;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external;
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address iTokenCollateral
) external;
function flashloan(
address recipient,
uint256 loanAmount,
bytes memory data
) external;
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external;
function updateInterest() external returns (bool);
function controller() external view returns (address);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function totalBorrows() external view returns (uint256);
function borrowBalanceCurrent(address _user) external returns (uint256);
function borrowBalanceStored(address _user) external view returns (uint256);
function borrowIndex() external view returns (uint256);
function getAccountSnapshot(address _account)
external
view
returns (
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function getCash() external view returns (uint256);
//----------------------------------
//********* Owner Actions **********
//----------------------------------
function _setNewReserveRatio(uint256 _newReserveRatio) external;
function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external;
function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external;
function _setController(IControllerInterface _newController) external;
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external;
function _withdrawReserves(uint256 _withdrawAmount) external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardDistributorV3 {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
/// @notice Emitted when iToken's Distribution borrow speed is updated
event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed);
/// @notice Emitted when iToken's Distribution supply speed is updated
event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed);
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IiToken.sol";
interface IPriceOracle {
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
!_initialized,
"Initializable: contract is already initialized"
);
_;
_initialized = true;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 {_setPendingOwner} and {_acceptOwner}.
*/
contract Ownable {
/**
* @dev Returns the address of the current owner.
*/
address payable public owner;
/**
* @dev Returns the address of the current pending owner.
*/
address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal {
owner = msg.sender;
emit NewOwner(address(0), msg.sender);
}
/**
* @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason.
* @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer.
* @param newPendingOwner New pending owner.
*/
function _setPendingOwner(address payable newPendingOwner)
external
onlyOwner
{
require(
newPendingOwner != address(0) && newPendingOwner != pendingOwner,
"_setPendingOwner: New owenr can not be zero address and owner has been set!"
);
// Gets current owner.
address oldPendingOwner = pendingOwner;
// Sets new pending owner.
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
/**
* @dev Accepts the admin rights, but only for pendingOwenr.
*/
function _acceptOwner() external {
require(
msg.sender == pendingOwner,
"_acceptOwner: Only for pending owner!"
);
// Gets current values for events.
address oldOwner = owner;
address oldPendingOwner = pendingOwner;
// Set the new contract owner.
owner = pendingOwner;
// Clear the pendingOwner.
pendingOwner = address(0);
emit NewOwner(oldOwner, owner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
uint256[50] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
library SafeRatioMath {
using SafeMathUpgradeable for uint256;
uint256 private constant BASE = 10**18;
uint256 private constant DOUBLE = 10**36;
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.add(y.sub(1)).div(y);
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(y).div(BASE);
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).div(y);
}
function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).add(y.sub(1)).div(y);
}
function tmul(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256 result) {
result = x.mul(y).mul(z).div(DOUBLE);
}
function rpow(
uint256 x,
uint256 n,
uint256 base
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(
iszero(iszero(x)),
iszero(eq(div(zx, x), z))
) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "./interface/IControllerInterface.sol";
import "./interface/IPriceOracle.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributor.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
/**
* @title dForce's lending controller Contract
* @author dForce
*/
contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Only expect to be called by iToken contract.
* @dev Add the market to the account's markets list for liquidity calculations
* @param _account The address of the account to modify
*/
function enterMarketFromiToken(address _account)
external
override
{
require(
_enterMarket(msg.sender, _account),
"enterMarketFromiToken: Only can be called by a supported iToken!"
);
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title dForce Lending Protocol's InterestRateModel Interface.
* @author dForce Team.
*/
interface IInterestRateModelInterface {
function isInterestRateModel() external view returns (bool);
/**
* @dev Calculates the current borrow interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @return The borrow rate per block (as a percentage, and scaled by 1e18).
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @dev Calculates the current supply interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @param reserveRatio The current reserve factor the market has.
* @return The supply rate per block (as a percentage, and scaled by 1e18).
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveRatio
) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IControllerAdminInterface {
/// @notice Emitted when an admin supports a market
event MarketAdded(
address iToken,
uint256 collateralFactor,
uint256 borrowFactor,
uint256 supplyCapacity,
uint256 borrowCapacity,
uint256 distributionFactor
);
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external;
/// @notice Emitted when new price oracle is set
event NewPriceOracle(address oldPriceOracle, address newPriceOracle);
function _setPriceOracle(address newOracle) external;
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(
uint256 oldCloseFactorMantissa,
uint256 newCloseFactorMantissa
);
function _setCloseFactor(uint256 newCloseFactorMantissa) external;
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(
uint256 oldLiquidationIncentiveMantissa,
uint256 newLiquidationIncentiveMantissa
);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external;
/// @notice Emitted when iToken's collateral factor is changed by admin
event NewCollateralFactor(
address iToken,
uint256 oldCollateralFactorMantissa,
uint256 newCollateralFactorMantissa
);
function _setCollateralFactor(
address iToken,
uint256 newCollateralFactorMantissa
) external;
/// @notice Emitted when iToken's borrow factor is changed by admin
event NewBorrowFactor(
address iToken,
uint256 oldBorrowFactorMantissa,
uint256 newBorrowFactorMantissa
);
function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa)
external;
/// @notice Emitted when iToken's borrow capacity is changed by admin
event NewBorrowCapacity(
address iToken,
uint256 oldBorrowCapacity,
uint256 newBorrowCapacity
);
function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity)
external;
/// @notice Emitted when iToken's supply capacity is changed by admin
event NewSupplyCapacity(
address iToken,
uint256 oldSupplyCapacity,
uint256 newSupplyCapacity
);
function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity)
external;
/// @notice Emitted when pause guardian is changed by admin
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
function _setPauseGuardian(address newPauseGuardian) external;
/// @notice Emitted when mint is paused/unpaused by admin or pause guardian
event MintPaused(address iToken, bool paused);
function _setMintPaused(address iToken, bool paused) external;
function _setAllMintPaused(bool paused) external;
/// @notice Emitted when redeem is paused/unpaused by admin or pause guardian
event RedeemPaused(address iToken, bool paused);
function _setRedeemPaused(address iToken, bool paused) external;
function _setAllRedeemPaused(bool paused) external;
/// @notice Emitted when borrow is paused/unpaused by admin or pause guardian
event BorrowPaused(address iToken, bool paused);
function _setBorrowPaused(address iToken, bool paused) external;
function _setAllBorrowPaused(bool paused) external;
/// @notice Emitted when transfer is paused/unpaused by admin or pause guardian
event TransferPaused(bool paused);
function _setTransferPaused(bool paused) external;
/// @notice Emitted when seize is paused/unpaused by admin or pause guardian
event SeizePaused(bool paused);
function _setSeizePaused(bool paused) external;
function _setiTokenPaused(address iToken, bool paused) external;
function _setProtocolPaused(bool paused) external;
event NewRewardDistributor(
address oldRewardDistributor,
address _newRewardDistributor
);
function _setRewardDistributor(address _newRewardDistributor) external;
}
interface IControllerPolicyInterface {
function beforeMint(
address iToken,
address account,
uint256 mintAmount
) external;
function afterMint(
address iToken,
address minter,
uint256 mintAmount,
uint256 mintedAmount
) external;
function beforeRedeem(
address iToken,
address redeemer,
uint256 redeemAmount
) external;
function afterRedeem(
address iToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemedAmount
) external;
function beforeBorrow(
address iToken,
address borrower,
uint256 borrowAmount
) external;
function afterBorrow(
address iToken,
address borrower,
uint256 borrowedAmount
) external;
function beforeRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function afterRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function beforeLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external;
function afterLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repaidAmount,
uint256 seizedAmount
) external;
function beforeSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizeAmount
) external;
function afterSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizedAmount
) external;
function beforeTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function afterTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function beforeFlashloan(
address iToken,
address to,
uint256 amount
) external;
function afterFlashloan(
address iToken,
address to,
uint256 amount
) external;
}
interface IControllerAccountEquityInterface {
function calcAccountEquity(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function liquidateCalculateSeizeTokens(
address iTokenBorrowed,
address iTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256);
}
interface IControllerAccountInterface {
function hasEnteredMarket(address account, address iToken)
external
view
returns (bool);
function getEnteredMarkets(address account)
external
view
returns (address[] memory);
/// @notice Emitted when an account enters a market
event MarketEntered(address iToken, address account);
function enterMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
function enterMarketFromiToken(address _account) external;
/// @notice Emitted when an account exits a market
event MarketExited(address iToken, address account);
function exitMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
/// @notice Emitted when an account add a borrow asset
event BorrowedAdded(address iToken, address account);
/// @notice Emitted when an account remove a borrow asset
event BorrowedRemoved(address iToken, address account);
function hasBorrowed(address account, address iToken)
external
view
returns (bool);
function getBorrowedAssets(address account)
external
view
returns (address[] memory);
}
interface IControllerInterface is
IControllerAdminInterface,
IControllerPolicyInterface,
IControllerAccountEquityInterface,
IControllerAccountInterface
{
/**
* @notice Security checks when updating the comptroller of a market, always expect to return true.
*/
function isController() external view returns (bool);
/**
* @notice Return all of the iTokens
* @return The list of iToken addresses
*/
function getAlliTokens() external view returns (address[] memory);
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardDistributor {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
function _setGlobalDistributionSpeeds(
uint256 borrowSpeed,
uint256 supplySpeed
) external;
/// @notice Emitted when iToken's Distribution speed is updated
event DistributionSpeedsUpdated(
address iToken,
uint256 borrowSpeed,
uint256 supplySpeed
);
function updateDistributionSpeed() external;
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function _setDistributionFactors(
address[] calldata iToken,
uint256[] calldata distributionFactors
) external;
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
| Update reward accrued in iTokens by the holders regardless of paused or not _holders The account to update _iTokens The _iTokens to update/ Update rewards for all _iTokens for holders | function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) public override {
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, false);
_updateDistributionState(_iToken, true);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], false);
_updateReward(_iToken, _holders[j], true);
}
}
}
| 1,318,007 |
pragma solidity >=0.5.16;
contract Election{
//Will model a learning material candidate
struct Candidate {
//TODO: Add more attribtes. Author, Price, Description
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Read/write candidates
mapping(uint => Candidate) public candidates;
// Store Candidates Count
uint public candidatesCount; //changed to = 0
// educational material added event
// event edMaterialAddedEvent(
// string name
// );
//Trigress when a vote is addred
event votedEvent(
uint indexed id
);
constructor () public {
}
function addCandidate(string memory name) public {
candidatesCount ++;
//candidates[candidatesCount] = Candidate(candidatesCount, _candidateNa, 0);
candidates[candidatesCount] = Candidate(candidatesCount, name, 0);
//trigger added ed material event
//emit edMaterialAddedEvent(name);
}
function vote (uint id) public {
id = id;
// require that they haven't voted beforecandidates[candidatesCount].name()
require(!voters[msg.sender]);
// require a valid candidate
require(id > 0 && id <= candidatesCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
candidates[id].voteCount ++;
// trigger voted event
emit votedEvent(id);
}
/// TODO: in app.js Computes the winning proposal taking all
/// previous votes into account.
function winningCandidate() public view
returns (uint candidateIndex)
{
uint winningVoteCount = 0;
for (uint p = 0; p <= candidatesCount; p++) {
if (candidates[p].voteCount > winningVoteCount) {
winningVoteCount = candidates[p].voteCount;
candidateIndex = p;
}
}
}
// TODO: In App.js function to get the index
// of the winner contained in the proposals array and then
// returns the name of the winner
function pickWinner() public view returns (string memory name)
{
name = candidates[winningCandidate()].name;
}
} | TODO: In App.js function to get the index of the winner contained in the proposals array and then returns the name of the winner | function pickWinner() public view returns (string memory name)
{
name = candidates[winningCandidate()].name;
}
| 5,351,002 |
./full_match/80001/0x68938d1f6B0657c95c75d589c16C4109FE1Aa7AD/sources/feature-v2/CentralizedAppealableArbitrator.sol | Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. _extraData Can be used to give additional info on the dispute to be created. return fee Amount to be paid./ Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. _disputeID ID of the dispute to be appealed. _extraData Can be used to give extra info on the appeal./ | function createDispute(uint256 _choices, bytes calldata _extraData)
public
payable
virtual
requireArbitrationFee(_extraData)
returns (uint256 disputeID)
function arbitrationCost(bytes calldata _extraData) public view virtual returns (uint256 fee);
function appeal(uint256 _disputeID, bytes calldata _extraData)
public
payable
virtual
requireAppealFee(_disputeID, _extraData)
{
emit AppealDecision(_disputeID, IArbitrable(msg.sender));
}
| 9,440,817 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IName
interface IName {
function name() external view returns (string memory);
}
// Part: IPoolFaucet
interface IPoolFaucet {
function userStates(address)
external
view
returns (uint128 lastExchangeRateMantissa, uint128 balance);
function deposit(uint256) external;
function claim(address) external;
}
// Part: IPoolTogether
interface IPoolTogether {
function depositTo(
address,
uint256,
address,
address
) external;
function withdrawInstantlyFrom(
address,
uint256,
address,
uint256
) external;
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: Uni
interface Uni {
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function apiVersion() external pure returns (string memory);
function withdraw(uint256 shares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.2";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay = 0;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: iearn-finance/[email protected]/BaseStrategyInitializable
abstract contract BaseStrategyInitializable is BaseStrategy {
constructor(address _vault) public BaseStrategy(_vault) {}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external {
_initialize(_vault, _strategist, _rewards, _keeper);
}
}
// File: StrategyDAIPoolTogether.sol
contract StrategyDAIPoolTogether is BaseStrategyInitializable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public wantPool;
address public poolToken;
address public unirouter;
address public bonus;
address public faucet;
address public ticket;
address public refer = address(0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7);
constructor(address _vault) public BaseStrategyInitializable(_vault) {}
function _initialize(
address _wantPool,
address _poolToken,
address _unirouter,
address _bonus,
address _faucet,
address _ticket
) internal {
wantPool = _wantPool;
poolToken = _poolToken;
unirouter = _unirouter;
bonus = _bonus;
faucet = _faucet;
ticket = _ticket;
IERC20(want).safeApprove(wantPool, uint256(-1));
IERC20(poolToken).safeApprove(unirouter, uint256(-1));
IERC20(bonus).safeApprove(unirouter, uint256(-1));
}
function initializeParent(
address _vault,
address _strategist,
address _rewards,
address _keeper
) public {
super._initialize(_vault, _strategist, _rewards, _keeper);
}
function initialize(
address _wantPool,
address _poolToken,
address _unirouter,
address _bonus,
address _faucet,
address _ticket
) external {
_initialize(
_wantPool,
_poolToken,
_unirouter,
_bonus,
_faucet,
_ticket
);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _wantPool,
address _poolToken,
address _unirouter,
address _bonus,
address _faucet,
address _ticket
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
StrategyDAIPoolTogether(newStrategy).initializeParent(
_vault,
_strategist,
_rewards,
_keeper
);
StrategyDAIPoolTogether(newStrategy).initialize(
_wantPool,
_poolToken,
_unirouter,
_bonus,
_faucet,
_ticket
);
}
function name() external view override returns (string memory) {
return
string(
abi.encodePacked("PoolTogether ", IName(address(want)).name())
);
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{
address[] memory protected = new address[](3);
// (aka want) is already protected by default
protected[0] = ticket;
protected[1] = poolToken;
protected[2] = bonus;
return protected;
}
// returns sum of all assets, realized and unrealized
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// We might need to return want to the vault
if (_debtOutstanding > 0) {
uint256 _amountFreed = 0;
(_amountFreed, _loss) = liquidatePosition(_debtOutstanding);
_debtPayment = Math.min(_amountFreed, _debtOutstanding);
}
// harvest() will track profit by estimated total assets compared to debt.
uint256 balanceOfWantBefore = balanceOfWant();
uint256 debt = vault.strategies(address(this)).totalDebt;
uint256 currentValue = estimatedTotalAssets();
// If we win we will have more value than debt!
// Let's convert tickets to want to calculate profit.
if (currentValue > debt) {
uint256 _amount = currentValue.sub(debt);
liquidatePosition(_amount);
}
claimReward();
uint256 _tokensAvailable = IERC20(poolToken).balanceOf(address(this));
if (_tokensAvailable > 0) {
_swap(_tokensAvailable, address(poolToken));
}
uint256 _bonusAvailable = IERC20(bonus).balanceOf(address(this));
if (_bonusAvailable > 0) {
_swap(_bonusAvailable, address(bonus));
}
uint256 balanceOfWantAfter = balanceOfWant();
if (balanceOfWantAfter > balanceOfWantBefore) {
_profit = balanceOfWantAfter.sub(balanceOfWantBefore);
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
// do not invest if we have more debt than want
if (_debtOutstanding > balanceOfWant()) {
return;
}
// Invest the rest of the want
uint256 _wantAvailable = balanceOfWant().sub(_debtOutstanding);
if (_wantAvailable > 0) {
IPoolTogether(wantPool).depositTo(
address(this),
_wantAvailable,
ticket,
refer
);
}
}
//v0.3.0 - liquidatePosition is emergency exit. Supplants exitPosition
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
if (balanceOfWant() < _amountNeeded) {
// We need to withdraw to get back more want
_withdrawSome(_amountNeeded.sub(balanceOfWant()));
}
uint256 balanceOfWant = balanceOfWant();
if (balanceOfWant >= _amountNeeded) {
_liquidatedAmount = _amountNeeded;
} else {
_liquidatedAmount = balanceOfWant;
_loss = (_amountNeeded.sub(balanceOfWant));
}
}
// withdraw some want from the vaults
function _withdrawSome(uint256 _amount) internal returns (uint256) {
uint256 balanceOfWantBefore = balanceOfWant();
IPoolTogether(wantPool).withdrawInstantlyFrom(
address(this),
_amount,
ticket,
1e20
);
uint256 balanceAfter = balanceOfWant();
return balanceAfter.sub(balanceOfWantBefore);
}
// transfers all tokens to new strategy
function prepareMigration(address _newStrategy) internal override {
// want is transferred by the base contract's migrate function
IERC20(poolToken).transfer(
_newStrategy,
IERC20(poolToken).balanceOf(address(this))
);
IERC20(bonus).transfer(
_newStrategy,
IERC20(bonus).balanceOf(address(this))
);
IERC20(ticket).transfer(
_newStrategy,
IERC20(ticket).balanceOf(address(this))
);
}
// returns value of total pool tickets
function balanceOfPool() public view returns (uint256) {
return IERC20(ticket).balanceOf(address(this));
}
// returns balance of want token
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
// swaps rewarded tokens for want
function _swap(uint256 _amountIn, address _token) internal {
address[] memory path = new address[](3);
path[0] = _token; // token to swap
path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // weth
path[2] = address(want);
Uni(unirouter).swapExactTokensForTokens(
_amountIn,
0,
path,
address(this),
now
);
}
// claims POOL from faucet
function claimReward() internal {
IPoolFaucet(faucet).claim(address(this));
}
function setReferrer(address _refer) external onlyGovernance {
refer = _refer;
}
} | Copied from https:github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol EIP-1167 bytecode | function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _wantPool,
address _poolToken,
address _unirouter,
address _bonus,
address _faucet,
address _ticket
) external returns (address newStrategy) {
bytes20 addressBytes = bytes20(address(this));
assembly {
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
StrategyDAIPoolTogether(newStrategy).initializeParent(
_vault,
_strategist,
_rewards,
_keeper
);
StrategyDAIPoolTogether(newStrategy).initialize(
_wantPool,
_poolToken,
_unirouter,
_bonus,
_faucet,
_ticket
);
}
| 12,101,983 |
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import "../base/Owned.sol";
import "./AuthereumProxy.sol";
contract AuthereumEnsManager {
function register(string calldata _label, address _owner) external {}
}
/**
* @title AuthereumProxyFactory
* @author Authereum Labs, Inc.
* @dev A factory that creates Authereum Proxies.
*/
contract AuthereumProxyFactory is Owned {
string constant public authereumProxyFactoryVersion = "2019111500";
bytes private initCode;
address private authereumEnsManagerAddress;
AuthereumEnsManager authereumEnsManager;
event InitCodeChanged(bytes initCode);
event AuthereumEnsManagerChanged(address indexed authereumEnsManager);
/// @dev Constructor
/// @param _implementation Address of the Authereum implementation
/// @param _authereumEnsManagerAddress Address for the Authereum ENS Manager contract
constructor(address _implementation, address _authereumEnsManagerAddress) public {
initCode = abi.encodePacked(type(AuthereumProxy).creationCode, uint256(_implementation));
authereumEnsManagerAddress = _authereumEnsManagerAddress;
authereumEnsManager = AuthereumEnsManager(authereumEnsManagerAddress);
emit InitCodeChanged(initCode);
emit AuthereumEnsManagerChanged(authereumEnsManagerAddress);
}
/**
* Setters
*/
/// @dev Setter for the proxy initCode
/// @param _initCode Init code off the AuthereumProxy and constructor
function setInitCode(bytes memory _initCode) public onlyOwner {
initCode = _initCode;
emit InitCodeChanged(initCode);
}
/// @dev Setter for the Authereum ENS Manager address
/// @param _authereumEnsManagerAddress Address of the new Authereum ENS Manager
function setAuthereumEnsManager(address _authereumEnsManagerAddress) public onlyOwner {
authereumEnsManagerAddress = _authereumEnsManagerAddress;
authereumEnsManager = AuthereumEnsManager(authereumEnsManagerAddress);
emit AuthereumEnsManagerChanged(authereumEnsManagerAddress);
}
/**
* Getters
*/
/// @dev Getter for the proxy initCode
/// @return Init code
function getInitCode() public view returns (bytes memory) {
return initCode;
}
/// @dev Getter for the private authereumEnsManager variable
/// @return Authereum Ens Manager
function getAuthereumEnsManager() public view returns (address) {
return authereumEnsManagerAddress;
}
/// @dev Create an Authereum Proxy and iterate through initialize data
/// @notice The bytes[] _initData is an array of initialize functions.
/// @notice This is used when a user creates an account e.g. on V5, but V1,2,3,
/// @notice etc. have state vars that need to be included.
/// @param _salt A uint256 value to add randomness to the account creation
/// @param _label Label for the user's Authereum ENS subdomain
/// @param _initData Array of initialize data
function createProxy(
uint256 _salt,
string memory _label,
bytes[] memory _initData
)
public
onlyOwner
returns (AuthereumProxy)
{
address payable addr;
bytes memory _initCode = initCode;
bytes32 salt = _getSalt(_salt, msg.sender);
// Create proxy
assembly {
addr := create2(0, add(_initCode, 0x20), mload(_initCode), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
// Loop through initializations of each version of the logic contract
bool success;
for (uint256 i = 0; i < _initData.length; i++) {
require(_initData[i].length != 0, "APF: Empty initialization data");
(success,) = addr.call(_initData[i]);
require(success, "APF: Unsuccessful account initialization");
}
// Set ENS name
authereumEnsManager.register(_label, addr);
return AuthereumProxy(addr);
}
/// @dev Generate a salt out of a uint256 value and the sender
/// @param _salt A uint256 value to add randomness to the account creation
/// @param _sender Sender of the transaction
function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_salt, _sender));
}
} | Getter for the proxy initCode return Init code | function getInitCode() public view returns (bytes memory) {
return initCode;
}
| 942,638 |
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title Batch Offsets
/// @author Adam Fuller (@azf20)
/// Randomly shuffles IDs in batches, given an overall token limit
/// Requirements: batchSize() divides perfectly into limit(), tokenIds start at 0
contract BatchOffsets {
error BatchNotRevealed();
event BatchRevealed(uint256 batch, uint256 batchSize, uint256 within, uint256 overall);
// counter of revealed batches
uint256 public revealedBatches;
// tracking the number of tokens in a batch
uint256 internal _batchSize;
function batchSize() public view virtual returns (uint256) {
return _batchSize;
}
// limit function, to be overriden by the importing contract
function limit() public view virtual returns (uint256) {
return 0;
}
// structure for an individual batch offset
struct BatchOffset {
uint256 seed; // the random number used to generate the offsets
uint256 within; // the offset of tokens within the batch
uint256 overall; // the offset of the batch overall, relative to other batches
}
// batches start at 1
mapping(uint256 => BatchOffset) public offsets;
mapping(uint256 => bool) private takenOffsets;
// Storing the offsets which are taken in a packed array of booleans
mapping(uint256 => uint256) public takenBitMap;
/// @notice Internal function to set an index as taken
/// @param index the index
function _setTaken(uint256 index) private {
uint256 takenWordIndex = index / 256;
uint256 takenBitIndex = index % 256;
takenBitMap[takenWordIndex] = takenBitMap[takenWordIndex] | (1 << takenBitIndex);
}
// set the batch offset for a batch, given a random number
function _setBatchOffset(uint256 _batch, uint256 random) internal {
// get an offset for within this batch
BatchOffset memory newBatchOffset;
newBatchOffset.seed = random;
newBatchOffset.within = random % batchSize();
// get an initial overall offset, out of the remaining slots
uint256 range = ((limit() / batchSize()) - revealedBatches);
random >>= 16;
uint256 overall = random % range;
// create an array to populate with the remaining available offsets
uint256[] memory offsetOptions = new uint256[](range);
uint256 counter;
uint256 word;
// fetch the first word from the packed booleans (makes it closer to O(1))
uint256 takenWord = takenBitMap[word];
// check which offsets are already taken from the full range
for(uint256 j=0; j<(limit() / batchSize()); j++) {
// if the offset is beyond the range of the current word, fetch the next word
if ((j / 256) > word) {
takenWord = takenBitMap[j / 256];
}
// check if a given offset is taken. If it is not, add it to the array of options
uint256 takenBitIndex = j % 256;
uint256 mask = (1 << takenBitIndex);
if(takenWord & mask != mask) {
offsetOptions[counter] = j;
counter += 1;
}
}
// the offset uses the initial offset to pick from the remaining available offsets
newBatchOffset.overall = offsetOptions[overall];
// set the selected offset as taken, and save the batch offset and increase the revealedBatches counter
_setTaken(newBatchOffset.overall);
offsets[_batch] = newBatchOffset;
revealedBatches += 1;
emit BatchRevealed(_batch, batchSize(), newBatchOffset.within, newBatchOffset.overall);
}
// helper to work out which batch an ID is from
function idToBatch(uint256 id) public view returns (uint256) {
return ((id) / batchSize()) + 1;
}
// get the shuffled ID, based on its batch's offsets
function getShuffledId(uint256 id) public virtual view returns (uint256) {
uint256 _batch = idToBatch(id);
if(offsets[_batch].seed == 0) revert BatchNotRevealed();
BatchOffset memory _offset = offsets[_batch];
uint256 within = (((id) % batchSize()) + _offset.within) % batchSize();
return (within * (limit() / batchSize())) + _offset.overall
;
}
}
| helper to work out which batch an ID is from | function idToBatch(uint256 id) public view returns (uint256) {
return ((id) / batchSize()) + 1;
}
| 13,135,451 |
./partial_match/42/0x7Dab59e2Ca3a043316C2039453989d8519756d92/sources/DisposableGovernance.sol | ERC20 interface/ | interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| 3,299,571 |
pragma solidity ^0.4.20;
/*
* ====================================*
*
* PROOF OF RIPPLE
* https://poripple.com/
* https://discord.gg/6AA5etr
*
* ====================================*
*
* -> How is Proof of Ripple different than other Proof Coin?
* Proof of Ripple is a more sustainable contract with the innovative 4X Wagering Requirement mechanics.
* The total amount of all sold tokens and reinvested tokens must be at least 4 times the total purchased tokens before you can withdraw.
*
* -> Here is an example illustrating how it works:
* Let say initially you purchased 500 PoRipple tokens, and sold all 500 tokens later, at that point, you cannot immediately withdraw because the 4X Wagering Requirement haven't met yet, you'll need to reinvest your balance in order to increase the total wagering amount.
* Now suppose the tokens price dropped a bit later on, and you're able to reinvest the dividends and get 750 tokens, so if you sell all 750 tokens, you'll be able to withdraw all your balance, because the 4X Wagering Requirement is fulfilled, i.e. Total Wagered Tokens (500 sell + 750 reinvest + 750 sell) = 4 x Total Purchased Tokens (500 initial purchase)
*
* -> What is the advantages of wagering:
* 1. Unlike all other PO clones, early buyers cannot just dump and exit in PoRipple, because they'll need to reinvest it back in order to fulfill the 4X Wagering Requirement.
* 2. It incentivize token holding, and gathering dividends instead of fomo dumping.
* 3. It induce higher volatility, more actions = more dividends for holders!
* 4. People will feel more comfortable buying in later stage.
*
* -> What?
* The original autonomous pyramid, improved:
* [x] More stable than ever, having withstood severe testnet abuse and attack attempts from our community!.
* [x] Audited, tested, and approved by known community security specialists such as tocsick and Arc.
* [X] New functionality; you can now perform partial sell orders. If you succumb to weak hands, you don't have to dump all of your bags!
* [x] New functionality; you can now transfer tokens between wallets. Trading is now possible from within the contract!
* [x] New Feature: PoS Masternodes! The first implementation of Ethereum Staking in the world! Vitalik is mad.
* [x] Masternodes: Holding 50 PoRipple Tokens allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract!
* [x] Masternodes: All players who enter the contract through your Masternode have 30% of their 20% dividends fee rerouted from the master-node, to the node-master!
*
* -> What about the last projects?
* Every programming member of the old dev team has been fired and/or killed by 232.
* The new dev team consists of seasoned, professional developers and has been audited by veteran solidity experts.
* Additionally, two independent testnet iterations have been used by hundreds of people; not a single point of failure was found.
*
* -> Who worked on this project?
* Trusted community from CryptoGaming
*
*/
contract ProofOfRipple {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier onlyWageredWithdraw() {
address _customerAddress = msg.sender;
require(wageringOf_[_customerAddress] >= SafeMath.mul(initialBuyinOf_[_customerAddress], wageringRequirement_));
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint256 timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint256 timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "ProofOfRipple";
string public symbol = "PoRipple";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 5; // 20% dividends on buy and sell and transfer
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 constant internal wageringRequirement_ = 4; // 4x is wagering requirement for the pyramid
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 50e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 0.4 ether; // only 0.4 eth premine
uint256 constant internal ambassadorQuota_ = 2 ether;
/*================================
= DATASETS =
================================*/
mapping(address => uint256) public initialBuyinOf_; // amount of tokens bought in pyramid
mapping(address => uint256) public wageringOf_; // wagering amount of tokens for the user
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function ProofOfRipple()
public
{
// add administrators here
administrators[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = true;
ambassadors_[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = true;
ambassadors_[0xFEA0904ACc8Df0F3288b6583f60B86c36Ea52AcD] = true;
ambassadors_[0x494952f01a30547d269aaF147e6226f940f5B041] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy, false);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0, false);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0, true);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
onlyWageredWithdraw()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// Update wagering balance of the user, add the sold amount of tokens
wageringOf_[_customerAddress] = SafeMath.add(wageringOf_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 20% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 20% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// Update wagering balance of the user, add the transfer amount tokens
wageringOf_[_customerAddress] = SafeMath.add(wageringOf_[_customerAddress], _amountOfTokens);
// Update wagering balance and buyin fee for the user tokens transfered to
initialBuyinOf_[_toAddress] = SafeMath.add(initialBuyinOf_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy, bool _isReinvest)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
if (_isReinvest) {
// Update the Wagering Balance for the customer
wageringOf_[msg.sender] = SafeMath.add(wageringOf_[msg.sender], _amountOfTokens);
} else {
// If it is not reinvest update initial Buy In amount
initialBuyinOf_[msg.sender] = SafeMath.add(initialBuyinOf_[msg.sender], _amountOfTokens);
}
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | Transfer tokens from the caller to a new holder. Remember, there's a 20% fee here as well./ setup make sure we have the requested tokens also disables transfers until ambassador phase is over ( we dont want whale premines ) withdraw all outstanding dividends first liquify 20% of the tokens that are transfered these are dispersed to shareholders burn the fee tokens exchange tokens Update wagering balance of the user, add the transfer amount tokens Update wagering balance and buyin fee for the user tokens transfered to update dividend trackers disperse dividends among holders fire event ERC20 | function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if(myDividends(true) > 0) withdraw();
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
wageringOf_[_customerAddress] = SafeMath.add(wageringOf_[_customerAddress], _amountOfTokens);
initialBuyinOf_[_toAddress] = SafeMath.add(initialBuyinOf_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
| 13,630,345 |
pragma solidity ^0.4.21;
/**
* Changes by https://www.docademic.com/
*/
/**
* @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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Destroyable is Ownable{
/**
* @notice Allows to destroy the contract and return the tokens to the owner.
*/
function destroy() public onlyOwner{
selfdestruct(owner);
}
}
interface Token {
function transfer(address _to, uint256 _value) external returns (bool);
function balanceOf(address who) view external returns (uint256);
}
contract TokenVault is Ownable, Destroyable {
using SafeMath for uint256;
Token public token;
/**
* @dev Constructor.
* @param _token The token address
*/
function TokenVault(address _token) public{
require(_token != address(0));
token = Token(_token);
}
/**
* @dev Get the token balance of the contract.
* @return _balance The token balance of this contract in wei
*/
function Balance() view public returns (uint256 _balance) {
return token.balanceOf(address(this));
}
/**
* @dev Get the token balance of the contract.
* @return _balance The token balance of this contract in ether
*/
function BalanceEth() view public returns (uint256 _balance) {
return token.balanceOf(address(this)) / 1 ether;
}
/**
* @dev Allows the owner to flush the tokens of the contract.
*/
function transferTokens(address _to, uint256 amount) public onlyOwner {
token.transfer(_to, amount);
}
/**
* @dev Allows the owner to flush the tokens of the contract.
*/
function flushTokens() public onlyOwner {
token.transfer(owner, token.balanceOf(address(this)));
}
/**
* @dev Allows the owner to destroy the contract and return the tokens to the owner.
*/
function destroy() public onlyOwner {
token.transfer(owner, token.balanceOf(address(this)));
selfdestruct(owner);
}
} | Constructor. _token The token address/ | function TokenVault(address _token) public{
require(_token != address(0));
token = Token(_token);
}
| 13,424,470 |
pragma solidity ^0.4.24;
import "zos-lib/contracts/Initializable.sol";
import "openzeppelin-eth/contracts/ownership/Ownable.sol";
import "openzeppelin-eth/contracts/lifecycle/Pausable.sol";
import "./AttributeRegistryInterface.sol";
import "./BasicJurisdictionInterface.sol";
/**
* @title Organizations validator contract .
*/
contract OrganizationsValidator is Initializable, Ownable, Pausable {
// declare events
event OrganizationAdded(address organization, string name);
event AttributeIssued(
address indexed organization,
address attributee
);
event AttributeRevoked(
address indexed organization,
address attributee
);
event IssuancePaused();
event IssuanceUnpaused();
// declare registry interface, used to request attributes from a jurisdiction
AttributeRegistryInterface private _registry;
// declare jurisdiction interface, used to set attributes in the jurisdiction
BasicJurisdictionInterface private _jurisdiction;
// declare the attribute ID required by the validator in order to transfer tokens
uint256 private _validAttributeTypeID;
// organizations are entities who can add attibutes to a number of accounts
struct Organization {
bool exists;
uint256 maximumAccounts; // NOTE: consider using uint248 to pack w/ exists
string name;
address[] accounts;
mapping(address => bool) issuedAccounts;
mapping(address => uint256) issuedAccountsIndex;
}
// organization data & issued attribute accounts are held in a struct mapping
mapping(address => Organization) private _organizations;
// accounts of all organizations are held in an array (enables enumeration)
address[] private _organizationAccounts;
// issuance of new attributes may be paused and unpaused by the validator.
bool private _issuancePaused;
/**
* @notice Add an organization at account `organization` and with an initial
* allocation of issuable attributes of `maximumIssuableAttributes`.
* @param organization address The account to assign to the organization.
* @param maximumIssuableAttributes uint256 The number of issuable accounts.
*/
function addOrganization(
address organization,
uint256 maximumIssuableAttributes,
string name
) external onlyOwner whenNotPaused {
// check that an empty account was not provided by mistake
require(organization != address(0), "must supply a valid account address");
// prevent existing organizations from being overwritten
require(
_organizations[organization].exists == false,
"an organization already exists at the provided account address"
);
// set up the organization in the organizations mapping
_organizations[organization].exists = true;
_organizations[organization].maximumAccounts = maximumIssuableAttributes;
_organizations[organization].name = name;
// add the organization to the end of the organizationAccounts array
_organizationAccounts.push(organization);
// log the addition of the organization
emit OrganizationAdded(organization, name);
}
/**
* @notice Modify an organization at account `organization` to change the
* number of issuable attributes to `maximumIssuableAttributes`.
* @param organization address The account assigned to the organization.
* @param maximumIssuableAttributes uint256 The number of issuable attributes.
* @dev Note that the maximum number of accounts cannot currently be set to a
* value less than the current number of issued accounts. This feature, coupled
* with the ability to revoke attributes, will *prevent an organization from
* being 'frozen' since the organization can remove an address and then add an
* arbitrary address in its place. Options to address this include a dedicated
* method for freezing organizations, or a special exception to the requirement
* below that allows the maximum to be set to 0 which will achieve the intended
* effect.
*/
function setMaximumIssuableAttributes(
address organization,
uint256 maximumIssuableAttributes
) external onlyOwner whenNotPaused {
require(
_organizations[organization].exists == true,
"an organization does not exist at the provided account address"
);
// make sure that maximum is not set below the current number of addresses
require(
_organizations[organization].accounts.length <= maximumIssuableAttributes,
"maximum cannot be set to amounts less than the current account total"
);
// set the organization's maximum addresses; a value == current freezes them
_organizations[organization].maximumAccounts = maximumIssuableAttributes;
}
/**
* @notice Add an attribute to account `account`.
* @param account address The account to issue the attribute to.
* @dev This function would need to be made payable to support jurisdictions
* that require fees in order to set attributes.
*/
function issueAttribute(
address account
) external whenNotPaused whenIssuanceNotPaused {
// check that an empty address was not provided by mistake
require(account != address(0), "must supply a valid account address");
// make sure the request is coming from a valid organization
require(
_organizations[msg.sender].exists == true,
"only organizations may issue attributes"
);
// ensure that the maximum has not been reached yet
uint256 maximum = uint256(_organizations[msg.sender].maximumAccounts);
require(
_organizations[msg.sender].accounts.length < maximum,
"the organization is not permitted to issue any additional attributes"
);
// assign the attribute to the jurisdiction (NOTE: a value is not required)
_jurisdiction.issueAttribute(account, _validAttributeTypeID, 0);
// ensure that the attribute was correctly assigned
require(
_registry.hasAttribute(account, _validAttributeTypeID) == true,
"attribute addition was not accepted by the jurisdiction"
);
// add the account to the mapping of issued accounts
_organizations[msg.sender].issuedAccounts[account] = true;
// add the index of the account to the mapping of issued accounts
uint256 index = _organizations[msg.sender].accounts.length;
_organizations[msg.sender].issuedAccountsIndex[account] = index;
// add the address to the end of the organization's `accounts` array
_organizations[msg.sender].accounts.push(account);
// log the addition of the new attributed account
emit AttributeIssued(msg.sender, account);
}
/**
* @notice Revoke an attribute from account `account`.
* @param account address The account to revoke the attribute from.
* @dev Organizations may still revoke attributes even after new issuance has
* been paused. This is the intended behavior, as it allows them to correct
* attributes they have issued that become compromised or otherwise erroneous.
*/
function revokeAttribute(address account) external whenNotPaused {
// check that an empty address was not provided by mistake
require(account != address(0), "must supply a valid account address");
// make sure the request is coming from a valid organization
require(
_organizations[msg.sender].exists == true,
"only organizations may revoke attributes"
);
// ensure that the account has been issued an attribute
require(
_organizations[msg.sender].issuedAccounts[account] &&
_organizations[msg.sender].accounts.length > 0,
"the organization is not permitted to revoke an unissued attribute"
);
// remove the attribute from the jurisdiction
_jurisdiction.revokeAttribute(account, _validAttributeTypeID);
// ensure that the attribute was correctly removed
require(
_registry.hasAttribute(account, _validAttributeTypeID) == false,
"attribute revocation was not accepted by the jurisdiction"
);
// get the account at the last index of the array
uint256 lastIndex = _organizations[msg.sender].accounts.length - 1;
address lastAccount = _organizations[msg.sender].accounts[lastIndex];
// get the index to delete
uint256 indexToDelete = _organizations[msg.sender].issuedAccountsIndex[account];
// set the account at indexToDelete to last account
_organizations[msg.sender].accounts[indexToDelete] = lastAccount;
// update the index of the account that was moved
_organizations[msg.sender].issuedAccountsIndex[lastAccount] = indexToDelete;
// remove the (now duplicate) account at the end by trimming the array
_organizations[msg.sender].accounts.length--;
// remove the account from the organization's issuedAccounts mapping as well
delete _organizations[msg.sender].issuedAccounts[account];
// log the addition of the new attributed account
emit AttributeRevoked(msg.sender, account);
}
/**
* @notice Count the number of organizations defined by the validator.
* @return The number of defined organizations.
*/
function countOrganizations() external view returns (uint256) {
return _organizationAccounts.length;
}
/**
* @notice Get the account of the organization at index `index`.
* @param index uint256 The index of the organization in question.
* @return The account of the organization.
*/
function getOrganization(uint256 index) external view returns (
address organization
) {
return _organizationAccounts[index];
}
/**
* @notice Get the accounts of all available organizations.
* @return A dynamic array containing all defined organization accounts.
*/
function getOrganizations() external view returns (address[] accounts) {
return _organizationAccounts;
}
/**
* @notice Get information about the organization at account `account`.
* @param organization address The account of the organization in question.
* @return The organization's existence, the maximum issuable accounts, the
* name of the organization, and a dynamic array containing issued accounts.
* @dev Note that an organization issuing numerous attributes may cause the
* function to fail, as the dynamic array could grow beyond a returnable size.
*/
function getOrganizationInformation(
address organization
) external view returns (
bool exists,
uint256 maximumAccounts,
string name,
address[] issuedAccounts
) {
return (
_organizations[organization].exists,
_organizations[organization].maximumAccounts,
_organizations[organization].name,
_organizations[organization].accounts
);
}
/**
* @notice Get the account of the utilized jurisdiction.
* @return The account of the jurisdiction.
*/
function getJurisdiction() external view returns (address) {
return address(_jurisdiction);
}
/**
* @notice Get the ID of the attribute type that the validator can issue.
* @return The ID of the attribute type.
*/
function getValidAttributeTypeID() external view returns (uint256) {
return _validAttributeTypeID;
}
/**
* @notice The initializer function for the OrganizationsValidator,
* with owner and pauser roles initially assigned to contract creator,
* and with an associated jurisdiction at `jurisdiction` and an assignable
* attribute type with ID `validAttributeTypeID`.
* @param jurisdiction address The account of the associated jurisdiction.
* @param validAttributeTypeID uint256 The ID of the attribute type to issue.
* @param sender address The account to be set as pauser and owner of the contract.
* @dev Note that it may be appropriate to require that the referenced
* jurisdiction supports the correct interface via EIP-165 and that the
* validator has been approved to issue attributes of the specified type when
* initializing the contract - it is not currently required.
*/
function initialize(
address jurisdiction,
uint256 validAttributeTypeID,
address sender
)
public
initializer
{
Ownable.initialize(sender);
Pausable.initialize(sender);
_issuancePaused = false;
_registry = AttributeRegistryInterface(jurisdiction);
_jurisdiction = BasicJurisdictionInterface(jurisdiction);
_validAttributeTypeID = validAttributeTypeID;
}
/**
* @notice Pause all issuance of new attributes by organizations.
*/
function pauseIssuance() public onlyOwner whenNotPaused whenIssuanceNotPaused {
_issuancePaused = true;
emit IssuancePaused();
}
/**
* @notice Unpause issuance of new attributes by organizations.
*/
function unpauseIssuance() public onlyOwner whenNotPaused {
require(_issuancePaused); // only allow unpausing when issuance is paused
_issuancePaused = false;
emit IssuanceUnpaused();
}
/**
* @notice Determine if attribute issuance is currently paused.
* @return True if issuance is currently paused, false otherwise.
*/
function issuanceIsPaused() public view returns (bool) {
return _issuancePaused;
}
/**
* @notice Modifier to allow issuing attributes only when not paused
*/
modifier whenIssuanceNotPaused() {
require(!_issuancePaused);
_;
}
} | Pause all issuance of new attributes by organizations./ | function pauseIssuance() public onlyOwner whenNotPaused whenIssuanceNotPaused {
_issuancePaused = true;
emit IssuancePaused();
}
| 12,974,542 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {DebtTokenBase} from './base/DebtTokenBase.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title VariableDebtToken
* @notice Implements a variable debt token to track the borrowing positions of users
* at variable rate mode
* @author Aave
**/
contract VariableDebtToken is DebtTokenBase, IVariableDebtToken {
using WadRayMath for uint256;
uint256 public constant DEBT_TOKEN_REVISION = 0x2;
constructor(
address pool,
address underlyingAsset,
string memory name,
string memory symbol,
address incentivesController
) public DebtTokenBase(pool, underlyingAsset, name, symbol, incentivesController) {}
/**
* @dev Gets the revision of the stable debt token implementation
* @return The debt token implementation revision
**/
function getRevision() internal pure virtual override returns (uint256) {
return DEBT_TOKEN_REVISION;
}
/**
* @dev Calculates the accumulated debt balance of the user
* @return The debt balance of the user
**/
function balanceOf(address user) public view virtual override returns (uint256) {
uint256 scaledBalance = super.balanceOf(user);
if (scaledBalance == 0) {
return 0;
}
return scaledBalance.rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET_ADDRESS));
}
/**
* @dev Mints debt token to the `onBehalfOf` address
* - Only callable by the LendingPool
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external override onlyLendingPool returns (bool) {
if (user != onBehalfOf) {
_decreaseBorrowAllowance(onBehalfOf, user, amount);
}
uint256 previousBalance = super.balanceOf(onBehalfOf);
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);
_mint(onBehalfOf, amountScaled);
emit Transfer(address(0), onBehalfOf, amount);
emit Mint(user, onBehalfOf, amount, index);
return previousBalance == 0;
}
/**
* @dev Burns user variable debt
* - Only callable by the LendingPool
* @param user The user whose debt is getting burned
* @param amount The amount getting burned
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external override onlyLendingPool {
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);
_burn(user, amountScaled);
emit Transfer(user, address(0), amount);
emit Burn(user, amount, index);
}
/**
* @dev Returns the principal debt balance of the user from
* @return The debt balance of the user since the last burn/mint action
**/
function scaledBalanceOf(address user) public view virtual override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users
* @return The total supply
**/
function totalSupply() public view virtual override returns (uint256) {
return
super.totalSupply().rayMul(POOL.getReserveNormalizedVariableDebt(UNDERLYING_ASSET_ADDRESS));
}
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return the scaled total supply
**/
function scaledTotalSupply() public view virtual override returns (uint256) {
return super.totalSupply();
}
/**
* @dev Returns the principal balance of the user and principal total supply.
* @param user The address of the user
* @return The principal balance of the user
* @return The principal total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
override
returns (uint256, uint256)
{
return (super.balanceOf(user), super.totalSupply());
}
/**
* @dev Returns the address of the incentives controller contract
* @return incentives address
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _incentivesController;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IScaledBalanceToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IAaveIncentivesController {
function handleAction(
address user,
uint256 userBalance,
uint256 totalSupply
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title Errors library
* @author Aave
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = ValidationLogic
* - MATH = Math libraries
* - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken)
* - AT = AToken
* - SDT = StableDebtToken
* - VDT = VariableDebtToken
* - LP = LendingPool
* - LPAPR = LendingPoolAddressesProviderRegistry
* - LPC = LendingPoolConfiguration
* - RL = ReserveLogic
* - LPCM = LendingPoolCollateralManager
* - P = Pausable
*/
library Errors {
//common errors
string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
//contract specific errors
string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0'
string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve'
string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen'
string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough'
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance'
string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.'
string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled'
string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected'
string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0'
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold'
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow'
string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled
string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed
string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'
string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed'
string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve'
string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve'
string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0'
string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral'
string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve'
string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met'
string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed'
string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow'
string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.'
string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent'
string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator'
string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28';
string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool'
string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself'
string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero'
string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized'
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve'
string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin'
string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered'
string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold'
string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated'
string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency'
string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate"
string public constant LPCM_NO_ERRORS = '46'; // 'No errors'
string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected
string public constant MATH_MULTIPLICATION_OVERFLOW = '48';
string public constant MATH_ADDITION_OVERFLOW = '49';
string public constant MATH_DIVISION_BY_ZERO = '50';
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128
string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128
string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint
string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57';
string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn
string public constant LP_FAILED_COLLATERAL_SWAP = '60';
string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61';
string public constant LP_REENTRANCY_NOT_ALLOWED = '62';
string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63';
string public constant LP_IS_PAUSED = '64'; // 'Pool is paused'
string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';
string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';
string public constant RC_INVALID_LTV = '67';
string public constant RC_INVALID_LIQ_THRESHOLD = '68';
string public constant RC_INVALID_LIQ_BONUS = '69';
string public constant RC_INVALID_DECIMALS = '70';
string public constant RC_INVALID_RESERVE_FACTOR = '71';
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';
string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';
string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74';
string public constant UL_INVALID_INDEX = '77';
string public constant LP_NOT_CONTRACT = '78';
string public constant SDT_STABLE_DEBT_OVERFLOW = '79';
string public constant SDT_BURN_EXCEEDS_BALANCE = '80';
enum CollateralManagerErrors {
NO_ERROR,
NO_COLLATERAL_AVAILABLE,
COLLATERAL_CANNOT_BE_LIQUIDATED,
CURRRENCY_NOT_BORROWED,
HEALTH_FACTOR_ABOVE_THRESHOLD,
NOT_ENOUGH_LIQUIDITY,
NO_ACTIVE_RESERVE,
HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,
INVALID_EQUAL_ASSETS_TO_SWAP,
FROZEN_RESERVE
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from '../../../interfaces/ILendingPool.sol';
import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol';
import {IDebtTokenBase} from '../../../interfaces/IDebtTokenBase.sol';
import {
VersionedInitializable
} from '../../libraries/aave-upgradeability/VersionedInitializable.sol';
import {IncentivizedERC20} from '../IncentivizedERC20.sol';
import {Errors} from '../../libraries/helpers/Errors.sol';
/**
* @title DebtTokenBase
* @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken
* @author Aave
*/
abstract contract DebtTokenBase is
IncentivizedERC20,
VersionedInitializable,
ICreditDelegationToken,
IDebtTokenBase
{
address public immutable UNDERLYING_ASSET_ADDRESS;
ILendingPool public immutable POOL;
mapping(address => mapping(address => uint256)) internal _borrowAllowances;
/**
* @dev Only lending pool can call functions marked by this modifier
**/
modifier onlyLendingPool {
require(_msgSender() == address(POOL), Errors.CT_CALLER_MUST_BE_LENDING_POOL);
_;
}
/**
* @dev The metadata of the token will be set on the proxy, that the reason of
* passing "NULL" and 0 as metadata
*/
constructor(
address pool,
address underlyingAssetAddress,
string memory name,
string memory symbol,
address incentivesController
) public IncentivizedERC20(name, symbol, 18, incentivesController) {
POOL = ILendingPool(pool);
UNDERLYING_ASSET_ADDRESS = underlyingAssetAddress;
}
/**
* @dev Initializes the debt token.
* @param name The name of the token
* @param symbol The symbol of the token
* @param decimals The decimals of the token
*/
function initialize(
uint8 decimals,
string memory name,
string memory symbol
) public initializer {
_setName(name);
_setSymbol(symbol);
_setDecimals(decimals);
emit Initialized(
UNDERLYING_ASSET_ADDRESS,
address(POOL),
address(_incentivesController),
decimals,
name,
symbol,
''
);
}
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external override {
_borrowAllowances[_msgSender()][delegatee] = amount;
emit BorrowAllowanceDelegated(_msgSender(), delegatee, UNDERLYING_ASSET_ADDRESS, amount);
}
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser)
external
view
override
returns (uint256)
{
return _borrowAllowances[fromUser][toUser];
}
/**
* @dev Being non transferrable, the debt token does not implement any of the
* standard ERC20 functions for transfer and allowance.
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
recipient;
amount;
revert('TRANSFER_NOT_SUPPORTED');
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
owner;
spender;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
spender;
amount;
revert('APPROVAL_NOT_SUPPORTED');
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
sender;
recipient;
amount;
revert('TRANSFER_NOT_SUPPORTED');
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
override
returns (bool)
{
spender;
addedValue;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override
returns (bool)
{
spender;
subtractedValue;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function _decreaseBorrowAllowance(
address delegator,
address delegatee,
uint256 amount
) internal {
uint256 newAllowance =
_borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH);
_borrowAllowances[delegator][delegatee] = newAllowance;
emit BorrowAllowanceDelegated(delegator, delegatee, UNDERLYING_ASSET_ADDRESS, newAllowance);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface ICreditDelegationToken {
event BorrowAllowanceDelegated(
address indexed fromUser,
address indexed toUser,
address asset,
uint256 amount
);
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external;
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IDebtTokenBase {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param incentivesController The address of the incentives controller for this aToken
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title VersionedInitializable
*
* @dev Helper contract to implement 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.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 private lastInitializedRevision = 0;
/**
* @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() {
uint256 revision = getRevision();
require(
initializing || isConstructor() || revision > lastInitializedRevision,
'Contract instance has already been initialized'
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
lastInitializedRevision = revision;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/**
* @dev returns the revision number of the contract
* Needs to be defined in the inherited class as a constant.
**/
function getRevision() internal pure virtual returns (uint256);
/**
* @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.
uint256 cs;
//solium-disable-next-line
assembly {
cs := extcodesize(address())
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title ERC20
* @notice Basic ERC20 implementation
* @author Aave, inspired by the Openzeppelin ERC20 implementation
**/
contract IncentivizedERC20 is Context, IERC20, IERC20Detailed {
using SafeMath for uint256;
IAaveIncentivesController internal immutable _incentivesController;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(
string memory name,
string memory symbol,
uint8 decimals,
address incentivesController
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_incentivesController = IAaveIncentivesController(incentivesController);
}
/**
* @return The name of the token
**/
function name() public view override returns (string memory) {
return _name;
}
/**
* @return The symbol of the token
**/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @return The decimals of the token
**/
function decimals() public view override returns (uint8) {
return _decimals;
}
/**
* @return The total supply of the token
**/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @return The balance of the token
**/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev Executes a transfer of tokens from _msgSender() to recipient
* @param recipient The recipient of the tokens
* @param amount The amount of tokens being transferred
* @return `true` if the transfer succeeds, `false` otherwise
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
emit Transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev Returns the allowance of spender on the tokens owned by owner
* @param owner The owner of the tokens
* @param spender The user allowed to spend the owner's tokens
* @return The amount of owner's tokens spender is allowed to spend
**/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev Allows `spender` to spend the tokens owned by _msgSender()
* @param spender The user allowed to spend _msgSender() tokens
* @return `true`
**/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so
* @param sender The owner of the tokens
* @param recipient The recipient of the tokens
* @param amount The amount of tokens being transferred
* @return `true` if the transfer succeeds, `false` otherwise
**/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
emit Transfer(sender, recipient, amount);
return true;
}
/**
* @dev Increases the allowance of spender to spend _msgSender() tokens
* @param spender The user allowed to spend on behalf of _msgSender()
* @param addedValue The amount being added to the allowance
* @return `true`
**/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Decreases the allowance of spender to spend _msgSender() tokens
* @param spender The user allowed to spend on behalf of _msgSender()
* @param subtractedValue The amount being subtracted to the allowance
* @return `true`
**/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
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 oldSenderBalance = _balances[sender];
_balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance');
uint256 oldRecipientBalance = _balances[recipient];
_balances[recipient] = _balances[recipient].add(amount);
if (address(_incentivesController) != address(0)) {
uint256 currentTotalSupply = _totalSupply;
_incentivesController.handleAction(sender, currentTotalSupply, oldSenderBalance);
if (sender != recipient) {
_incentivesController.handleAction(recipient, currentTotalSupply, oldRecipientBalance);
}
}
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.add(amount);
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.add(amount);
if (address(_incentivesController) != address(0)) {
_incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.sub(amount);
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance');
if (address(_incentivesController) != address(0)) {
_incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
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 _setName(string memory newName) internal {
_name = newName;
}
function _setSymbol(string memory newSymbol) internal {
_symbol = newSymbol;
}
function _setDecimals(uint8 newDecimals) internal {
_decimals = newDecimals;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: agpl-3.0
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);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from './IERC20.sol';
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
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;
}
}
| IVariableDebtToken Aave Defines the basic interface for a variable debt token./ | interface IVariableDebtToken is IScaledBalanceToken {
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
event Burn(address indexed user, uint256 amount, uint256 index);
function burn(
address user,
uint256 amount,
uint256 index
) external;
function getIncentivesController() external view returns (IAaveIncentivesController);
pragma solidity 0.6.12;
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
}
| 410,985 |
./full_match/5/0xA0176eB3F609081cefeCdADC07c8a45869038B6E/sources/contracts/L1/messaging/L1StandardBridge.sol | Performs the logic for deposits by informing the L2 Deposited Token contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom) _l1Token Address of the L1 ERC20 we are depositing _l2Token Address of the L1 respective L2 ERC20 _from Account to pull the deposit from on L1 _to Account to give the deposit to on L2 _amount Amount of the ERC20 to deposit. _l2Gas Gas limit required to complete the deposit on L2. _data Optional data to forward to L2. This data is provided solely as a convenience for external contracts. Aside from enforcing a maximum length, these contracts provide no guarantees about its content./ When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if _from is an EOA or address(0). slither-disable-next-line reentrancy-events, reentrancy-benign Construct calldata for _l2Token.finalizeDeposit(_to, _amount) | function _initiateERC20Deposit(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
) internal {
IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount);
if (_l1Token == Lib_PredeployAddresses.VMT) {
_l2Token = Lib_PredeployAddresses.OVM_ETH;
}
bytes memory message = abi.encodeWithSelector(
IL2ERC20Bridge.finalizeDeposit.selector,
_l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
}
| 7,039,262 |
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.2;
// interface need to claim rouge tokens from contract and handle upgraded functions
abstract contract IERC20 {
function balanceOf(address owner) public view virtual returns (uint256);
function transfer(address to, uint256 amount) public virtual;
function allowance(address owner, address spender)
public
view
virtual
returns (uint256);
function totalSupply() public view virtual returns (uint256);
}
// interface to potential future upgraded contract,
// only essential write functions that need check that this contract is caller
abstract contract IUpgradedToken {
function transferByLegacy(
address sender,
address to,
uint256 amount
) public virtual returns (bool);
function transferFromByLegacy(
address sender,
address from,
address to,
uint256 amount
) public virtual returns (bool);
function approveByLegacy(
address sender,
address spender,
uint256 amount
) public virtual;
}
//
// The ultimate ERC20 token contract for TecraCoin project
//
contract TcrToken {
//
// ERC20 basic information
//
uint8 public constant decimals = 8;
string public constant name = "TecraCoin";
string public constant symbol = "TCR";
uint256 private _totalSupply;
uint256 public constant maxSupply = 21000000000000000;
string public constant version = "1";
uint256 public immutable getChainId;
//
// other flags, data and constants
//
address public owner;
address public newOwner;
bool public paused;
bool public deprecated;
address public upgradedAddress;
bytes32 public immutable DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
string private constant ERROR_DAS = "Different array sizes";
string private constant ERROR_BTL = "Balance too low";
string private constant ERROR_ATL = "Allowance too low";
string private constant ERROR_OO = "Only Owner";
//
// events
//
event Transfer(address indexed from, address indexed to, uint256 value);
event Paused();
event Unpaused();
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event AddedToBlacklist(address indexed account);
event RemovedFromBlacklist(address indexed account);
//
// data stores
//
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint256) private _balances;
mapping(address => bool) public isBlacklisted;
mapping(address => bool) public isBlacklistAdmin;
mapping(address => bool) public isMinter;
mapping(address => bool) public isPauser;
mapping(address => uint256) public nonces;
//
// contract constructor
//
constructor() {
owner = msg.sender;
getChainId = block.chainid;
// EIP712 Domain
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256(bytes(version)),
block.chainid,
address(this)
)
);
}
//
// "approve"
//
function approve(address spender, uint256 amount) external {
if (deprecated) {
return
IUpgradedToken(upgradedAddress).approveByLegacy(
msg.sender,
spender,
amount
);
}
_approve(msg.sender, spender, amount);
}
//
// "burnable"
//
function burn(uint256 amount) external {
require(_balances[msg.sender] >= amount, ERROR_BTL);
_burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount) external {
require(_allowances[msg.sender][from] >= amount, ERROR_ATL);
require(_balances[from] >= amount, ERROR_BTL);
_approve(msg.sender, from, _allowances[msg.sender][from] - amount);
_burn(from, amount);
}
//
// "transfer"
//
function transfer(address to, uint256 amount) external returns (bool) {
if (deprecated) {
return
IUpgradedToken(upgradedAddress).transferByLegacy(
msg.sender,
to,
amount
);
}
require(_balances[msg.sender] >= amount, ERROR_BTL);
_transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool) {
if (deprecated) {
return
IUpgradedToken(upgradedAddress).transferFromByLegacy(
msg.sender,
from,
to,
amount
);
}
_allowanceTransfer(msg.sender, from, to, amount);
return true;
}
//
// non-ERC20 functionality
//
// Rouge tokens and ETH withdrawal
function acquire(address token) external onlyOwner {
if (token == address(0)) {
payable(owner).transfer(address(this).balance);
} else {
uint256 amount = IERC20(token).balanceOf(address(this));
require(amount > 0, ERROR_BTL);
IERC20(token).transfer(owner, amount);
}
}
//
// "blacklist"
//
function addBlacklister(address user) external onlyOwner {
isBlacklistAdmin[user] = true;
}
function removeBlacklister(address user) external onlyOwner {
isBlacklistAdmin[user] = false;
}
modifier onlyBlacklister {
require(isBlacklistAdmin[msg.sender], "Not a Blacklister");
_;
}
modifier notOnBlacklist(address user) {
require(!isBlacklisted[user], "Address on blacklist");
_;
}
function addBlacklist(address user) external onlyBlacklister {
isBlacklisted[user] = true;
emit AddedToBlacklist(user);
}
function removeBlacklist(address user) external onlyBlacklister {
isBlacklisted[user] = false;
emit RemovedFromBlacklist(user);
}
function burnBlackFunds(address user) external onlyOwner {
require(isBlacklisted[user], "Address not on blacklist");
_burn(user, _balances[user]);
}
//
// "bulk transfer"
//
// transfer to list of address-amount
function bulkTransfer(address[] calldata to, uint256[] calldata amount)
external
returns (bool)
{
require(to.length == amount.length, ERROR_DAS);
for (uint256 i = 0; i < to.length; i++) {
require(_balances[msg.sender] >= amount[i], ERROR_BTL);
_transfer(msg.sender, to[i], amount[i]);
}
return true;
}
// transferFrom to list of address-amount
function bulkTransferFrom(
address from,
address[] calldata to,
uint256[] calldata amount
) external returns (bool) {
require(to.length == amount.length, ERROR_DAS);
for (uint256 i = 0; i < to.length; i++) {
_allowanceTransfer(msg.sender, from, to[i], amount[i]);
}
return true;
}
// send same amount to multiple addresses
function bulkTransfer(address[] calldata to, uint256 amount)
external
returns (bool)
{
require(_balances[msg.sender] >= amount * to.length, ERROR_BTL);
for (uint256 i = 0; i < to.length; i++) {
_transfer(msg.sender, to[i], amount);
}
return true;
}
// send same amount to multiple addresses by allowance
function bulkTransferFrom(
address from,
address[] calldata to,
uint256 amount
) external returns (bool) {
require(_balances[from] >= amount * to.length, ERROR_BTL);
for (uint256 i = 0; i < to.length; i++) {
_allowanceTransfer(msg.sender, from, to[i], amount);
}
return true;
}
//
// "mint"
//
modifier onlyMinter {
require(isMinter[msg.sender], "Not a Minter");
_;
}
function addMinter(address user) external onlyOwner {
isMinter[user] = true;
}
function removeMinter(address user) external onlyOwner {
isMinter[user] = false;
}
function mint(address to, uint256 amount) external onlyMinter {
_balances[to] += amount;
_totalSupply += amount;
require(_totalSupply < maxSupply, "You can not mine that much");
emit Transfer(address(0), to, amount);
}
//
// "ownable"
//
modifier onlyOwner {
require(msg.sender == owner, ERROR_OO);
_;
}
function giveOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() external {
require(msg.sender == newOwner, ERROR_OO);
newOwner = address(0);
owner = msg.sender;
}
//
// "pausable"
//
function addPauser(address user) external onlyOwner {
isPauser[user] = true;
}
function removePauser(address user) external onlyOwner {
isPauser[user] = false;
}
modifier onlyPauser {
require(isPauser[msg.sender], "Not a Pauser");
_;
}
modifier notPaused {
require(!paused, "Contract is paused");
_;
}
function pause() external onlyPauser notPaused {
paused = true;
emit Paused();
}
function unpause() external onlyPauser {
require(paused, "Contract not paused");
paused = false;
emit Unpaused();
}
//
// "permit"
// Uniswap integration EIP-2612
//
function permit(
address user,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "permit: EXPIRED");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
user,
spender,
value,
nonces[user]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == user,
"permit: INVALID_SIGNATURE"
);
_approve(user, spender, value);
}
//
// upgrade contract
//
function upgrade(address token) external onlyOwner {
deprecated = true;
upgradedAddress = token;
}
//
// ERC20 view functions
//
function balanceOf(address account) external view returns (uint256) {
if (deprecated) {
return IERC20(upgradedAddress).balanceOf(account);
}
return _balances[account];
}
function allowance(address account, address spender)
external
view
returns (uint256)
{
if (deprecated) {
return IERC20(upgradedAddress).allowance(account, spender);
}
return _allowances[account][spender];
}
function totalSupply() external view returns (uint256) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
}
return _totalSupply;
}
//
// internal functions
//
function _approve(
address account,
address spender,
uint256 amount
) private notOnBlacklist(account) notOnBlacklist(spender) notPaused {
_allowances[account][spender] = amount;
emit Approval(account, spender, amount);
}
function _allowanceTransfer(
address spender,
address from,
address to,
uint256 amount
) private {
require(_allowances[from][spender] >= amount, ERROR_ATL);
require(_balances[from] >= amount, ERROR_BTL);
// exception for Uniswap "approve forever"
if (_allowances[from][spender] != type(uint256).max) {
_approve(from, spender, _allowances[from][spender] - amount);
}
_transfer(from, to, amount);
}
function _burn(address from, uint256 amount) private notPaused {
_balances[from] -= amount;
_totalSupply -= amount;
emit Transfer(from, address(0), amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private notOnBlacklist(from) notOnBlacklist(to) notPaused {
require(to != address(0), "Use burn instead");
require(from != address(0), "What a Terrible Failure");
_balances[from] -= amount;
_balances[to] += amount;
emit Transfer(from, to, amount);
}
}
// rav3n_pl was here | "bulk transfer" transfer to list of address-amount | function bulkTransfer(address[] calldata to, uint256[] calldata amount)
external
returns (bool)
{
require(to.length == amount.length, ERROR_DAS);
for (uint256 i = 0; i < to.length; i++) {
require(_balances[msg.sender] >= amount[i], ERROR_BTL);
_transfer(msg.sender, to[i], amount[i]);
}
return true;
}
| 10,054,097 |
./partial_match/1/0xe300C0DBDd784Cc2CD1A86b2126Fc95629389F91/sources/contracts/modules/interest-rate/InterestRateCredit.sol | update last timestamp in storage | function _accrueInterest(bytes32 id, uint256 drawnBalance, uint256 facilityBalance) internal returns (uint256) {
Rate memory rate = rates[id];
uint256 timespan = block.timestamp - rate.lastAccrued;
rates[id].lastAccrued = block.timestamp;
return (_calculateInterestOwed(rate.dRate, drawnBalance, timespan) +
_calculateInterestOwed(rate.fRate, (facilityBalance - drawnBalance), timespan));
}
| 15,654,130 |
./partial_match/1/0xE8F0f997e5000BbD7A9E1dbc1FdBB4E43f72407A/sources/VOLUM.sol | Prforms allowance transfer of asset balance between holders adding specified comment. Resolves asset implementation contract for the caller and forwards there arguments along with the caller address. _from holder address to take from. _icap recipient ICAP address to give to. _value amount to transfer. _reference transfer comment to be included in a EToken2's Transfer event. return success./ | function transferFromToICAPWithReference(
address _from,
bytes32 _icap,
uint _value,
string _reference)
public returns(bool) {
return _getAsset()._performTransferFromToICAPWithReference(
_from,
_icap,
_value,
_reference,
msg.sender
);
}
| 15,921,313 |
pragma solidity ^0.4.23;
contract fileSale {
uint constant depth = 14;
uint constant length = 2;
uint constant n = 16384;
enum stage {created, initialized, accepted, keyRevealed, finished}
stage public phase = stage.created;
uint public timeout;
address sender;
address receiver;
uint price = 100; // in wei
bytes32 keyCommit ;
bytes32 ciphertextRoot ;
bytes32 fileRoot ;
bytes32 public key;
// function modifier to only allow calling the function in the right phase only from the correct party
modifier allowed(address p, stage s) {
require(phase == s);
require(now < timeout);
require(msg.sender == p);
_;
}
// go to next phase
function nextStage() internal {
phase = stage(uint(phase) + 1);
timeout = now + 10 minutes;
}
// constructor is initialize function
function ininitialize (address _receiver, uint _price, bytes32 _keyCommit, bytes32 _ciphertextRoot, bytes32 _fileRoot) public {
require(phase == stage.created);
receiver = _receiver;
sender = msg.sender;
price = _price;
keyCommit = _keyCommit;
ciphertextRoot = _ciphertextRoot;
fileRoot = _fileRoot;
nextStage();
}
// function accept
function accept () allowed(receiver, stage.initialized) payable public {
require (msg.value >= price);
nextStage();
}
// function revealKey (key)
function revealKey (bytes32 _key) allowed(sender, stage.accepted) public {
require(keyCommit == keccak256(_key));
key = _key;
nextStage();
}
// function complain about wrong hash of file
function noComplain () allowed(receiver, stage.keyRevealed) public {
sender.call.value(price);
phase = stage.created;
}
// function complain about wrong hash of file
function complainAboutRoot (bytes32 _Zm, bytes32[depth] _proofZm) allowed( receiver, stage.keyRevealed) public {
require (vrfy(2*(n-1), _Zm, _proofZm));
if (cryptSmall(2*(n-1), _Zm) != fileRoot){
receiver.call.value(price);
phase = stage.created;
}
}
// function complain about wrong hash of two inputs
function complainAboutLeaf (uint _indexOut, uint _indexIn,
bytes32 _Zout, bytes32[length] _Zin1, bytes32[length] _Zin2, bytes32[depth] _proofZout,
bytes32[depth] _proofZin) allowed( receiver, stage.keyRevealed) public {
require (vrfy(_indexOut, _Zout, _proofZout));
bytes32 Xout = cryptSmall(_indexOut, _Zout);
require (vrfy(_indexIn, keccak256(_Zin1), _proofZin));
require (_proofZin[0] == keccak256(_Zin2));
if (Xout != keccak256(cryptLarge(_indexIn, _Zin1), cryptLarge(_indexIn+1, _Zin2))) {
receiver.call.value(price);
phase = stage.created;
}
}
// function complain about wrong hash of two inputs
function complainAboutNode (uint _indexOut, uint _indexIn,
bytes32 _Zout, bytes32 _Zin1, bytes32 _Zin2, bytes32[depth] _proofZout,
bytes32[depth] _proofZin) allowed(receiver, stage.keyRevealed) public {
require (vrfy(_indexOut, _Zout, _proofZout));
bytes32 Xout = cryptSmall(_indexOut, _Zout);
require (vrfy(_indexIn, _Zin1, _proofZin));
require (_proofZin[0] == _Zin2);
if (Xout != keccak256(cryptSmall(_indexIn, _Zin1), cryptSmall(_indexIn+1, _Zin2))) {
receiver.call.value(price);
phase = stage.created;
}
}
// refund function is called in case some party did not contribute in time
function refund () public {
require (now > timeout);
if (phase == stage.accepted) {
receiver.call.value(price);
phase = stage.created;
}
else if (phase >= stage.keyRevealed) {
sender.call.value(price);
phase = stage.created;
}
}
// function to both encrypt and decrypt text chunks with key k
function cryptLarge (uint _index, bytes32[length] _ciphertext) public view returns (bytes32[length]){
_index = _index*length;
for (uint i = 0; i < length; i++){
_ciphertext[i] = keccak256(_index, key) ^ _ciphertext[i];
_index++;
}
return _ciphertext;
}
// function to decrypt hashes of the merkle tree
function cryptSmall (uint _index, bytes32 _ciphertext) public view returns (bytes32){
return keccak256(_index, key) ^ _ciphertext;
}
// function to verify Merkle Tree proofs
function vrfy(uint _index, bytes32 _value, bytes32[depth] _proof) public view returns (bool){
for (uint i = 0; i < 3; i++){
if ((_index & 1<<i)>>i == 1)
_value = keccak256(_proof[3 -i], _value);
else
_value = keccak256(_value, _proof[3 -i]);
}
return (_value == ciphertextRoot);
}
} | function complain about wrong hash of file | function noComplain () allowed(receiver, stage.keyRevealed) public {
sender.call.value(price);
phase = stage.created;
}
| 13,133,858 |
./full_match/100/0x0Ac7ac8C6Eb5BbBEbE2d02E6B6f5B2B8e05759f1/sources/contracts/BetExpress.sol | Calculate the odds of a bet with an amount for the sub-bet subBets. This method additionally returns `outcomesIndexes` and `virtualFunds` that can assist in subsequent calculations. amount The amount of tokens to bet. subBets The SubBet array. See {IBetExpress-SubBet}. return conditionOdds The betting odds for each sub-bet. return expressOdds The resulting betting odds. return outcomesIndexes The predicted outcome index for each sub-bet. return virtualFunds The condition virtual funds for each sub-bet./ | function _calcOdds(SubBet[] memory subBets, uint128 amount)
internal
view
returns (
uint64[] memory conditionOdds,
uint256 expressOdds,
uint256[] memory outcomesIndexes,
uint128[2][] memory virtualFunds
)
{
uint256 length = subBets.length;
if (length < 2) revert TooFewSubbets();
expressOdds = FixedMath.ONE;
uint256 oddsSum;
conditionOdds = new uint64[](length);
outcomesIndexes = new uint256[](length);
virtualFunds = new uint128[2][](length);
uint64[] memory conditionMargins = new uint64[](length);
{
uint256[] memory gameIds = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
SubBet memory subBet = subBets[i];
ICondition.Condition memory condition = core.getCondition(
subBet.conditionId
);
_conditionIsRunning(condition, subBet.conditionId);
{
uint256 gameId = condition.gameId;
for (uint256 j = 0; j < i; j++) {
if (gameIds[j] == gameId)
revert SameGameIdsNotAllowed();
}
gameIds[i] = gameId;
}
uint256 outcomeIndex = CoreTools.getOutcomeIndex(
condition,
subBet.outcomeId
);
uint256 odds = CoreTools.calcOdds(
condition.virtualFunds,
0,
outcomeIndex,
0
);
expressOdds = expressOdds.mul(odds);
oddsSum += odds;
outcomesIndexes[i] = outcomeIndex;
virtualFunds[i] = condition.virtualFunds;
conditionMargins[i] = condition.margin;
}
}
{
uint128 subBetAmount = (((expressOdds - FixedMath.ONE) * amount) /
(oddsSum - length * FixedMath.ONE)).toUint128();
expressOdds = FixedMath.ONE;
for (uint256 i = 0; i < length; i++) {
uint256 outcomeIndex = outcomesIndexes[i];
uint64 adjustedOdds = uint64(
CoreTools.calcOdds(
virtualFunds[i],
subBetAmount,
outcomeIndex,
conditionMargins[i]
)
);
conditionOdds[i] = adjustedOdds;
expressOdds = expressOdds.mul(adjustedOdds);
}
}
}
| 14,285,465 |
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../interface/RocketStorageInterface.sol";
/// @title Base settings / modifiers for each contract in Rocket Pool
/// @author David Rugendyke
abstract contract RocketBase {
// Calculate using this as the base
uint256 constant calcBase = 1 ether;
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
RocketStorageInterface rocketStorage = RocketStorageInterface(0);
/*** Modifiers **********************************************************/
/**
* @dev Throws if called by any sender that doesn't match a Rocket Pool network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered node
*/
modifier onlyRegisteredNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node DAO member
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered minipool
*/
modifier onlyRegisteredMinipool(address _minipoolAddress) {
require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool");
_;
}
/**
* @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled)
*/
modifier onlyGuardian() {
require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian");
_;
}
/*** Methods **********************************************************/
/// @dev Set the main Rocket Storage address
constructor(RocketStorageInterface _rocketStorageAddress) {
// Update the contract address
rocketStorage = RocketStorageInterface(_rocketStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist)
function getContractAddressUnsafe(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(bytes(contractName).length > 0, "Contract not found");
// Return
return contractName;
}
/// @dev Get revert error message from a .call method
function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/*** Rocket Storage Methods ****************************************/
// Note: Unused helpers have been removed to keep contract sizes down
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); }
/// @dev Storage arithmetic methods
function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); }
function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); }
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../../../RocketBase.sol";
import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsInterface.sol";
// Settings in RP which the DAO will have full control over
// This settings contract enables storage using setting paths with namespaces, rather than explicit set methods
abstract contract RocketDAOProtocolSettings is RocketBase, RocketDAOProtocolSettingsInterface {
// The namespace for a particular group of settings
bytes32 settingNameSpace;
// Only allow updating from the DAO proposals contract
modifier onlyDAOProtocolProposal() {
// If this contract has been initialised, only allow access from the proposals contract
if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAOProtocolProposals") == msg.sender, "Only DAO Protocol Proposals contract can update a setting");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) {
// Apply the setting namespace
settingNameSpace = keccak256(abi.encodePacked("dao.protocol.setting.", _settingNameSpace));
}
/*** Uints ****************/
// A general method to return any setting given the setting path is correct, only accepts uints
function getSettingUint(string memory _settingPath) public view override returns (uint256) {
return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAOProtocolProposal {
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Bools ****************/
// A general method to return any setting given the setting path is correct, only accepts bools
function getSettingBool(string memory _settingPath) public view override returns (bool) {
return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAOProtocolProposal {
// Update setting now
setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Addresses ****************/
// A general method to return any setting given the setting path is correct, only accepts addresses
function getSettingAddress(string memory _settingPath) external view override returns (address) {
return getAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingAddress(string memory _settingPath, address _value) virtual external override onlyDAOProtocolProposal {
// Update setting now
setAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "./RocketDAOProtocolSettings.sol";
import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsNodeInterface.sol";
// Network auction settings
contract RocketDAOProtocolSettingsNode is RocketDAOProtocolSettings, RocketDAOProtocolSettingsNodeInterface {
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketDAOProtocolSettings(_rocketStorageAddress, "node") {
// Set version
version = 1;
// Initialize settings on deployment
if(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) {
// Apply settings
setSettingBool("node.registration.enabled", false);
setSettingBool("node.deposit.enabled", false);
setSettingUint("node.per.minipool.stake.minimum", 0.1 ether); // 10% of user ETH value
setSettingUint("node.per.minipool.stake.maximum", 1.5 ether); // 150% of user ETH value
// Settings initialised
setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true);
}
}
// Node registrations currently enabled
function getRegistrationEnabled() override external view returns (bool) {
return getSettingBool("node.registration.enabled");
}
// Node deposits currently enabled
function getDepositEnabled() override external view returns (bool) {
return getSettingBool("node.deposit.enabled");
}
// Minimum RPL stake per minipool as a fraction of assigned user ETH value
function getMinimumPerMinipoolStake() override external view returns (uint256) {
return getSettingUint("node.per.minipool.stake.minimum");
}
// Maximum RPL stake per minipool as a fraction of assigned user ETH value
function getMaximumPerMinipoolStake() override external view returns (uint256) {
return getSettingUint("node.per.minipool.stake.maximum");
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketStorageInterface {
// Deploy status
function getDeployedStatus() external view returns (bool);
// Guardian
function getGuardian() external view returns(address);
function setGuardian(address _newAddress) external;
function confirmGuardian() external;
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
// Arithmetic
function addUint(bytes32 _key, uint256 _amount) external;
function subUint(bytes32 _key, uint256 _amount) external;
// Protected storage
function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProtocolSettingsInterface {
function getSettingUint(string memory _settingPath) external view returns (uint256);
function setSettingUint(string memory _settingPath, uint256 _value) external;
function getSettingBool(string memory _settingPath) external view returns (bool);
function setSettingBool(string memory _settingPath, bool _value) external;
function getSettingAddress(string memory _settingPath) external view returns (address);
function setSettingAddress(string memory _settingPath, address _value) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProtocolSettingsNodeInterface {
function getRegistrationEnabled() external view returns (bool);
function getDepositEnabled() external view returns (bool);
function getMinimumPerMinipoolStake() external view returns (uint256);
function getMaximumPerMinipoolStake() external view returns (uint256);
} | Node registrations currently enabled | function getRegistrationEnabled() override external view returns (bool) {
return getSettingBool("node.registration.enabled");
}
| 6,216,261 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./Input.sol";
import "./Bytes.sol";
import { ScaleStruct } from "./Scale.struct.sol";
pragma experimental ABIEncoderV2;
library Scale {
using Input for Input.Data;
using Bytes for bytes;
// Vec<Event> Event = <index, Data> Data = {accountId, EthereumAddress, types, Balance}
// bytes memory hexData = hex"102403d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27ddac17f958d2ee523a2206206994597c13d831ec700000e5fa31c00000000000000000000002404d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27ddac17f958d2ee523a2206206994597c13d831ec70100e40b5402000000000000000000000024038eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48b20bd5d04be54f870d5c0d3ca85d82b34b8364050000d0b72b6a000000000000000000000024048eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48b20bd5d04be54f870d5c0d3ca85d82b34b8364050100c817a8040000000000000000000000";
function decodeLockEvents(Input.Data memory data)
internal
pure
returns (ScaleStruct.LockEvent[] memory)
{
uint32 len = decodeU32(data);
ScaleStruct.LockEvent[] memory events = new ScaleStruct.LockEvent[](len);
for(uint i = 0; i < len; i++) {
events[i] = ScaleStruct.LockEvent({
index: data.decodeBytesN(2).toBytes2(0),
sender: decodeAccountId(data),
recipient: decodeEthereumAddress(data),
token: decodeEthereumAddress(data),
value: decodeBalance(data)
});
}
return events;
}
function decodeIssuingEvent(Input.Data memory data)
internal
pure
returns (ScaleStruct.IssuingEvent[] memory)
{
uint32 len = decodeU32(data);
ScaleStruct.IssuingEvent[] memory events = new ScaleStruct.IssuingEvent[](len);
for(uint i = 0; i < len; i++) {
bytes2 index = data.decodeBytesN(2).toBytes2(0);
uint8 eventType = data.decodeU8();
if (eventType == 0) {
events[i] = ScaleStruct.IssuingEvent({
index: index,
eventType: eventType,
backing: decodeEthereumAddress(data),
token: decodeEthereumAddress(data),
target: decodeEthereumAddress(data),
recipient: payable(address(0)),
sender: address(0),
value: 0
});
} else if (eventType == 1) {
events[i] = ScaleStruct.IssuingEvent({
index: index,
eventType: eventType,
backing: decodeEthereumAddress(data),
sender: decodeEthereumAddress(data),
recipient: decodeEthereumAddress(data),
token: decodeEthereumAddress(data),
target: decodeEthereumAddress(data),
value: decode256Balance(data)
});
}
}
return events;
}
/** Header */
// export interface Header extends Struct {
// readonly parentHash: Hash;
// readonly number: Compact<BlockNumber>;
// readonly stateRoot: Hash;
// readonly extrinsicsRoot: Hash;
// readonly digest: Digest;
// }
function decodeStateRootFromBlockHeader(
bytes memory header
) internal pure returns (bytes32 root) {
uint8 offset = decodeCompactU8aOffset(header[32]);
assembly {
root := mload(add(add(header, 0x40), offset))
}
return root;
}
function decodeBlockNumberFromBlockHeader(
bytes memory header
) internal pure returns (uint32 blockNumber) {
Input.Data memory data = Input.from(header);
// skip parentHash(Hash)
data.shiftBytes(32);
blockNumber = decodeU32(data);
}
// little endian
function decodeMMRRoot(Input.Data memory data)
internal
pure
returns (bytes memory prefix, bytes4 methodID, uint32 width, bytes32 root)
{
prefix = decodePrefix(data);
methodID = data.decodeBytes4();
width = decodeU32(data);
root = data.decodeBytes32();
}
function decodeAuthorities(Input.Data memory data)
internal
pure
returns (bytes memory prefix, bytes4 methodID, uint32 nonce, address[] memory authorities)
{
prefix = decodePrefix(data);
methodID = data.decodeBytes4();
nonce = decodeU32(data);
uint authoritiesLength = decodeU32(data);
authorities = new address[](authoritiesLength);
for(uint i = 0; i < authoritiesLength; i++) {
authorities[i] = decodeEthereumAddress(data);
}
}
// decode authorities prefix
// (crab, darwinia)
function decodePrefix(Input.Data memory data)
internal
pure
returns (bytes memory prefix)
{
prefix = decodeByteArray(data);
}
// decode Ethereum address
function decodeEthereumAddress(Input.Data memory data)
internal
pure
returns (address payable addr)
{
bytes memory bys = data.decodeBytesN(20);
assembly {
addr := mload(add(bys,20))
}
}
// decode Balance
function decodeBalance(Input.Data memory data)
internal
pure
returns (uint128)
{
bytes memory balance = data.decodeBytesN(16);
return uint128(reverseBytes16(balance.toBytes16(0)));
}
// decode 256bit Balance
function decode256Balance(Input.Data memory data)
internal
pure
returns (uint256)
{
bytes32 v = data.decodeBytes32();
bytes16[2] memory split = [bytes16(0), 0];
assembly {
mstore(split, v)
mstore(add(split, 16), v)
}
uint256 heigh = uint256(uint128(reverseBytes16(split[1]))) << 128;
uint256 low = uint256(uint128(reverseBytes16(split[0])));
return heigh + low;
}
// decode darwinia network account Id
function decodeAccountId(Input.Data memory data)
internal
pure
returns (bytes32 accountId)
{
accountId = data.decodeBytes32();
}
// decodeReceiptProof receives Scale Codec of Vec<Vec<u8>> structure,
// the Vec<u8> is the proofs of mpt
// returns (bytes[] memory proofs)
function decodeReceiptProof(Input.Data memory data)
internal
pure
returns (bytes[] memory proofs)
{
proofs = decodeVecBytesArray(data);
}
// decodeVecBytesArray accepts a Scale Codec of type Vec<Bytes> and returns an array of Bytes
function decodeVecBytesArray(Input.Data memory data)
internal
pure
returns (bytes[] memory v)
{
uint32 vecLenght = decodeU32(data);
v = new bytes[](vecLenght);
for(uint i = 0; i < vecLenght; i++) {
uint len = decodeU32(data);
v[i] = data.decodeBytesN(len);
}
return v;
}
// decodeByteArray accepts a byte array representing a SCALE encoded byte array and performs SCALE decoding
// of the byte array
function decodeByteArray(Input.Data memory data)
internal
pure
returns (bytes memory v)
{
uint32 len = decodeU32(data);
if (len == 0) {
return v;
}
v = data.decodeBytesN(len);
return v;
}
// decodeU32 accepts a byte array representing a SCALE encoded integer and performs SCALE decoding of the smallint
function decodeU32(Input.Data memory data) internal pure returns (uint32) {
uint8 b0 = data.decodeU8();
uint8 mode = b0 & 3;
require(mode <= 2, "scale decode not support");
if (mode == 0) {
return uint32(b0) >> 2;
} else if (mode == 1) {
uint8 b1 = data.decodeU8();
uint16 v = uint16(b0) | (uint16(b1) << 8);
return uint32(v) >> 2;
} else if (mode == 2) {
uint8 b1 = data.decodeU8();
uint8 b2 = data.decodeU8();
uint8 b3 = data.decodeU8();
uint32 v = uint32(b0) |
(uint32(b1) << 8) |
(uint32(b2) << 16) |
(uint32(b3) << 24);
return v >> 2;
}
}
// encodeByteArray performs the following:
// b -> [encodeInteger(len(b)) b]
function encodeByteArray(bytes memory src)
internal
pure
returns (bytes memory des, uint256 bytesEncoded)
{
uint256 n;
(des, n) = encodeU32(uint32(src.length));
bytesEncoded = n + src.length;
des = abi.encodePacked(des, src);
}
// encodeU32 performs the following on integer i:
// i -> i^0...i^n where n is the length in bits of i
// if n < 2^6 write [00 i^2...i^8 ] [ 8 bits = 1 byte encoded ]
// if 2^6 <= n < 2^14 write [01 i^2...i^16] [ 16 bits = 2 byte encoded ]
// if 2^14 <= n < 2^30 write [10 i^2...i^32] [ 32 bits = 4 byte encoded ]
function encodeU32(uint32 i) internal pure returns (bytes memory, uint256) {
// 1<<6
if (i < 64) {
uint8 v = uint8(i) << 2;
bytes1 b = bytes1(v);
bytes memory des = new bytes(1);
des[0] = b;
return (des, 1);
// 1<<14
} else if (i < 16384) {
uint16 v = uint16(i << 2) + 1;
bytes memory des = new bytes(2);
des[0] = bytes1(uint8(v));
des[1] = bytes1(uint8(v >> 8));
return (des, 2);
// 1<<30
} else if (i < 1073741824) {
uint32 v = uint32(i << 2) + 2;
bytes memory des = new bytes(4);
des[0] = bytes1(uint8(v));
des[1] = bytes1(uint8(v >> 8));
des[2] = bytes1(uint8(v >> 16));
des[3] = bytes1(uint8(v >> 24));
return (des, 4);
} else {
revert("scale encode not support");
}
}
// convert BigEndian to LittleEndian
function reverseBytes16(bytes16 input) internal pure returns (bytes16 v) {
v = input;
// swap bytes
v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = (v >> 64) | (v << 64);
}
function decodeCompactU8aOffset(bytes1 input0) public pure returns (uint8) {
bytes1 flag = input0 & bytes1(hex"03");
if (flag == hex"00") {
return 1;
} else if (flag == hex"01") {
return 2;
} else if (flag == hex"02") {
return 4;
}
uint8 offset = (uint8(input0) >> 2) + 4 + 1;
return offset;
}
}
| decodeVecBytesArray accepts a Scale Codec of type Vec<Bytes> and returns an array of Bytes | function decodeVecBytesArray(Input.Data memory data)
internal
pure
returns (bytes[] memory v)
{
uint32 vecLenght = decodeU32(data);
v = new bytes[](vecLenght);
for(uint i = 0; i < vecLenght; i++) {
uint len = decodeU32(data);
v[i] = data.decodeBytesN(len);
}
return v;
}
| 1,805,997 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
import "./YapeLibrary.sol";
import "../helpers/uni-v2/libraries/SafeMath.sol";
import "../helpers/uni-v2/interfaces/IUniswapV2Pair.sol";
import "../helpers/uni-v2/interfaces/IUniswapV2Factory.sol";
import "../helpers/uni-v2/interfaces/IUniswapV2Router02.sol";
import "../helpers/uni-v2/interfaces/IERC20.sol";
import "../helpers/uni-v2/interfaces/IWETH.sol";
import "../helpers/uni-v2/libraries/SafeMath.sol";
import "../helpers/uni-v2/libraries/TransferHelper.sol";
contract YapeRouter is IUniswapV2Router02 {
using SafeMath for uint256;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "UniswapV2Router: EXPIRED");
_;
}
constructor(address _factory, address _WETH) {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) = YapeLibrary.getReserves(
factory,
tokenA,
tokenB
);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = YapeLibrary.quote(
amountADesired,
reserveA,
reserveB
);
if (amountBOptimal <= amountBDesired) {
require(
amountBOptimal >= amountBMin,
"UniswapV2Router: INSUFFICIENT_B_AMOUNT"
);
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = YapeLibrary.quote(
amountBDesired,
reserveB,
reserveA
);
assert(amountAOptimal <= amountADesired);
require(
amountAOptimal >= amountAMin,
"UniswapV2Router: INSUFFICIENT_A_AMOUNT"
);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pair = YapeLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = YapeLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH)
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (uint256 amountA, uint256 amountB)
{
address pair = YapeLibrary.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint256 amount0, uint256 amount1) = IUniswapV2Pair(pair).burn(to);
(address token0, ) = YapeLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0
? (amount0, amount1)
: (amount1, amount0);
require(
amountA >= amountAMin,
"UniswapV2Router: INSUFFICIENT_A_AMOUNT"
);
require(
amountB >= amountBMin,
"UniswapV2Router: INSUFFICIENT_B_AMOUNT"
);
}
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (uint256 amountToken, uint256 amountETH)
{
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountA, uint256 amountB) {
address pair = YapeLibrary.pairFor(factory, tokenA, tokenB);
uint256 value = approveMax ? type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountA, amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
}
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
)
external
virtual
override
returns (uint256 amountToken, uint256 amountETH)
{
address pair = YapeLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountToken, amountETH) = removeLiquidityETH(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(
token,
to,
IERC20(token).balanceOf(address(this))
);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountETH) {
address pair = YapeLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = YapeLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2
? YapeLibrary.pairFor(factory, output, path[i + 2])
: _to;
IUniswapV2Pair(YapeLibrary.pairFor(factory, input, output)).swap(
amount0Out,
amount1Out,
to,
new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
amounts = YapeLibrary.getAmountsOut(factory, amountIn, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
YapeLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
amounts = YapeLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= amountInMax,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
YapeLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "UniswapV2Router: INVALID_PATH");
amounts = YapeLibrary.getAmountsOut(factory, msg.value, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT"
);
IWETH(WETH).deposit{value: amounts[0]}();
assert(
IWETH(WETH).transfer(
YapeLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
}
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "UniswapV2Router: INVALID_PATH");
amounts = YapeLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= amountInMax,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
YapeLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "UniswapV2Router: INVALID_PATH");
amounts = YapeLibrary.getAmountsOut(factory, amountIn, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
YapeLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "UniswapV2Router: INVALID_PATH");
amounts = YapeLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= msg.value,
"UniswapV2Router: EXCESSIVE_INPUT_AMOUNT"
);
IWETH(WETH).deposit{value: amounts[0]}();
assert(
IWETH(WETH).transfer(
YapeLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0])
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = YapeLibrary.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(
YapeLibrary.pairFor(factory, input, output)
);
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(
reserveInput
);
amountOutput = YapeLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2
? YapeLibrary.pairFor(factory, output, path[i + 2])
: _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
YapeLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >=
amountOutMin,
"UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
require(path[0] == WETH, "UniswapV2Router: INVALID_PATH");
uint256 amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(
IWETH(WETH).transfer(
YapeLibrary.pairFor(factory, path[0], path[1]),
amountIn
)
);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >=
amountOutMin,
"UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WETH, "UniswapV2Router: INVALID_PATH");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
YapeLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint256 amountOut = IERC20(WETH).balanceOf(address(this));
require(
amountOut >= amountOutMin,
"UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT"
);
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual override returns (uint256 amountB) {
return YapeLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountOut) {
return YapeLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountIn) {
return YapeLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return YapeLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return YapeLibrary.getAmountsIn(factory, amountOut, path);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
import "../helpers/uni-v2/libraries/SafeMath.sol";
import "../helpers/uni-v2/interfaces/IUniswapV2Pair.sol";
library YapeLibrary {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "YapeLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "YapeLibrary: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"9c5b6412b8c28ce222942af3b8a56134dbbe627ed1e5cbf1879cd45c026a49ca" // init code hash
)
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(
pairFor(factory, tokenA, tokenB)
).getReserves();
(reserveA, reserveB) = tokenA == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "YapeLibrary: INSUFFICIENT_AMOUNT");
require(
reserveA > 0 && reserveB > 0,
"YapeLibrary: INSUFFICIENT_LIQUIDITY"
);
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "YapeLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"YapeLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "YapeLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"YapeLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "YapeLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(
factory,
path[i],
path[i + 1]
);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "YapeLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(
factory,
path[i - 1],
path[i]
);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
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;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
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;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
import "./IUniswapV2Router01.sol";
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
interface IUniswapV2Router01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
interface IERC20 {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view 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);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x095ea7b3, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: APPROVE_FAILED"
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: TRANSFER_FAILED"
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x23b872dd, from, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper: TRANSFER_FROM_FAILED"
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
| performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "YapeLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(
factory,
path[i],
path[i + 1]
);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 12,267,828 |
/** Copyright (c) 2018, ZSC Dev Team
* 2018-10-19: v0.00.01
*/
pragma solidity ^0.4.25;
// pragma experimental ABIEncoderV2;
import "../utillib/LibString.sol";
import "../utillib/LibInt.sol";
import "../common/pausable.sol";
import "../common/delegate.sol";
contract InsuranceCompany {
// function update(string _key, string _data) external;
// function remove(string _key) external;
// function size() external view returns (uint);
// function getByKey(string _key) external view returns (int, string);
// function getById(uint _id) external view returns (int, string, string);
function getAll() external view returns (int, string);
}
contract InsuranceTemplate {
// function update(string _key, string _data) external;
// function remove(string _key) external;
// function size() external view returns (uint);
function getByKey(string _key) external view returns (int, string);
// function getById(uint _id) external view returns (int, string, string);
}
contract InsuranceUser {
function add(string _userKey, string _template, string _data) external;
function remove(string _key) external;
// function size() public view returns (uint);
function exist(uint8 _type, string _key0, address _key1) public view returns (bool);
function getByKey(uint8 _type, string _key) external view returns (int, string);
// function getById(uint8 _type, uint _id) external view returns (int, string);
}
contract InsurancePolicy {
function add(string _userKey, string _templateKey, string _policyKey, string _data) external;
function addElement(string _key, string _elementKey, string _data) external;
function remove(string _key) external;
// function size() public view returns (uint);
function getByKey(uint8 _type, string _key) external view returns (int, string);
// function getById(uint8 _type, uint _id) external view returns (int, string);
function getKeys(uint _id, uint _count) external view returns (int, string);
}
contract InsuranceIntegral {
function claim(address _account, uint8 _type) public returns (bool);
// function mint(address _account, uint _value) public returns (bool);
function burn(address _account, uint _value) public;
function transfer(address _owner, address _to, uint _value) public returns (bool);
function addTrace(address _account, uint8 _scene, uint _time, uint _value, address _from, address _to) public;
function removeTrace(address _account) public;
// function updateThreshold(uint8 _type, uint _threshold) public;
// function updateCap(uint _newCap) public;
function trace(address _account, uint _startTime, uint _endTime) public view returns (string);
function traceSize(address _account, uint8 _scene, uint _time) public view returns (uint);
function threshold(uint8 _type) public view returns (uint);
// function cap() public view returns (uint);
// function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
}
contract Insurance is Pausable, Delegate {
using LibString for *;
using LibInt for *;
struct strArray {
/** @dev id start from '1', '0' means no exists */
mapping(string => uint) ids_;
mapping(uint => string) strs_;
uint sum_;
}
address private companyAddr_;
address private templateAddr_;
address private userAddr_;
address private policyAddr_;
address private integralAddr_;
string[] private keys_;
/** @dev string(original policy key) => uint(max id)
* @eg [email protected]_PingAn_Life => 9
*/
mapping(string => uint) private maxIds_;
/** @dev string(user key) => strArray(policy keys) */
mapping(string => strArray) private policyKeys_;
modifier _checkCompanyAddr() {
require(0 != companyAddr_);
_;
}
modifier _checkTemplateAddr() {
require(0 != templateAddr_);
_;
}
modifier _checkUserAddr() {
require(0 != userAddr_);
_;
}
modifier _checkPolicyAddr() {
require(0 != policyAddr_);
_;
}
modifier _checkIntegralAddr() {
require(0 != integralAddr_);
_;
}
modifier _onlyAdminOrHigher() {
require(checkDelegate(msg.sender, 2));
_;
}
modifier _onlyReaderOrHigher() {
require(checkDelegate(msg.sender, 3));
_;
}
constructor() public {
companyAddr_ = address(0);
templateAddr_ = address(0);
userAddr_ = address(0);
policyAddr_ = address(0);
integralAddr_ = address(0);
}
/** @dev Destroy the contract. */
function destroy() public _onlyOwner {
super.kill();
}
/** @dev Add policy key.
* @param _userKey string The key of user.
* @param _policyKey string The key of policy.
*/
function _addPolicyKey(string _userKey, string _policyKey) private {
// check exists
if (0 != policyKeys_[_userKey].ids_[_policyKey]) {
return;
}
uint sum = ++policyKeys_[_userKey].sum_;
policyKeys_[_userKey].ids_[_policyKey] = sum;
policyKeys_[_userKey].strs_[sum] = _policyKey;
}
/** @dev Remove policy key.
* @param _userKey string The key of user.
* @param _policyKey string The key of policy.
*/
function _removePolicyKey(string _userKey, string _policyKey) private {
uint sum = policyKeys_[_userKey].sum_;
// check sum
require(0 != sum);
// check exists
require(0 != policyKeys_[_userKey].ids_[_policyKey]);
string memory key2 = policyKeys_[_userKey].strs_[sum];
// check exists
require(0 != policyKeys_[_userKey].ids_[key2]);
// swap
uint id1 = policyKeys_[_userKey].ids_[_policyKey];
uint id2 = policyKeys_[_userKey].ids_[key2];
policyKeys_[_userKey].strs_[id1] = key2;
policyKeys_[_userKey].strs_[id2] = _policyKey;
policyKeys_[_userKey].ids_[_policyKey] = id2;
policyKeys_[_userKey].ids_[key2] = id1;
delete policyKeys_[_userKey].strs_[sum];
policyKeys_[_userKey].ids_[_policyKey] = 0;
policyKeys_[_userKey].sum_ --;
}
/** @dev Remove policy.
* @param _policyKey string The key of policy.
*/
function _removePolicy(string _policyKey) private {
_policyKey.split("_", keys_);
// 1. remove policy key for insurance_user_policy.sol
_removePolicyKey(keys_[0], _policyKey);
// 2. remove policy for insurance_policy.sol
InsurancePolicy(policyAddr_).remove(_policyKey);
}
/** @dev Setup.
* @param _companyAddr address The address of template contract.
* @param _templateAddr address The address of template contract.
* @param _userAddr address The address of user contract.
* @param _policyAddr address The address of policy contract.
* @param _integralAddr address The address of integral contract.
*/
function setup(address _companyAddr, address _templateAddr, address _userAddr, address _policyAddr, address _integralAddr) external whenNotPaused _onlyOwner {
// check params
require(address(0) != _companyAddr);
require(address(0) != _templateAddr);
require(address(0) != _userAddr);
require(address(0) != _policyAddr);
require(address(0) != _integralAddr);
companyAddr_ = _companyAddr;
templateAddr_ = _templateAddr;
userAddr_ = _userAddr;
policyAddr_ = _policyAddr;
integralAddr_ = _integralAddr;
}
/** @dev called by the owner to pause, triggers stopped state
*/
function pause() public whenNotPaused _onlyOwner {
super.pause();
}
/** @dev called by the owner to unpause, returns to normal state
*/
function unpause() public whenPaused _onlyOwner {
super.unpause();
}
/** @return true if the contract is paused, false otherwise.
*/
function paused() public view _onlyOwner returns (bool) {
return super.paused();
}
/** @dev Get all companies' info.
* @return The error code and the all companies' data.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function companyGetAll() external view whenNotPaused _onlyReaderOrHigher _checkCompanyAddr returns (int, string) {
return InsuranceCompany(companyAddr_).getAll();
}
/** @dev Get template info by key.
* @param _key string The key of template.
* @return The error code and the data of template info.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function templateGetByKey(string _key) external view whenNotPaused _onlyReaderOrHigher _checkTemplateAddr returns (int, string) {
return InsuranceTemplate(templateAddr_).getByKey(_key);
}
/** @dev Add user.
* @param _userKey string The key of user.
* @param _templateKey string The key of user template.
* @param _data string The JSON data of user.
* @param _time uint The trace time(UTC), including TZ and DST.
*/
function userAdd(string _userKey, string _templateKey, string _data, uint _time) external whenNotPaused _onlyAdminOrHigher _checkTemplateAddr _checkUserAddr _checkIntegralAddr {
// check param
require(0 != bytes(_userKey).length);
require(0 != bytes(_templateKey).length);
require(0 != bytes(_data).length);
string memory template = "";
int error = 0;
(error, template) = InsuranceTemplate(templateAddr_).getByKey(_templateKey);
require(0 == error);
InsuranceUser(userAddr_).add(_userKey, template, _data);
address account = _userKey.toAddress();
if (InsuranceIntegral(integralAddr_).claim(account, 0)) {
InsuranceIntegral(integralAddr_).addTrace(account, 0, _time, InsuranceIntegral(integralAddr_).threshold(0), integralAddr_, account);
}
}
/** @dev Remove user.
* @param _key string The key of user.
*/
function userRemove(string _key) external whenNotPaused _onlyOwner _checkUserAddr _checkPolicyAddr _checkIntegralAddr {
// check param
require(0 != bytes(_key).length);
// remove integral
address account = _key.toAddress();
require(InsuranceUser(userAddr_).exist(1, "", account));
uint value = InsuranceIntegral(integralAddr_).balanceOf(account);
if (0 < value) {
InsuranceIntegral(integralAddr_).burn(account, value);
}
// remove integral trace
InsuranceIntegral(integralAddr_).removeTrace(account);
// remove policies
uint size = policyKeys_[_key].sum_;
for (uint i=0; i<size; i++) {
string memory policyKey = policyKeys_[_key].strs_[1];
_removePolicy(policyKey);
}
// remove user
InsuranceUser(userAddr_).remove(_key);
}
/** @dev User check in.
* @param _account address The user address.
* @param _time uint The trace time(UTC), including TZ and DST.
*/
function userCheckIn(address _account, uint _time) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _account));
require(0 == InsuranceIntegral(integralAddr_).traceSize(_account, 2, _time));
if (InsuranceIntegral(integralAddr_).claim(_account, 2)) {
InsuranceIntegral(integralAddr_).addTrace(_account, 2, _time, InsuranceIntegral(integralAddr_).threshold(2), integralAddr_, _account);
}
}
/** @dev Check that if user exist
* @param _type uint8 The info type (0: key is string, 1: key is address).
* @param _key0 string The key of user for string.
* @param _key1 address The key of user for address.
* @return true/false.
*/
function userExist(uint8 _type, string _key0, address _key1) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (bool) {
return InsuranceUser(userAddr_).exist(_type, _key0, _key1);
}
/** @dev Get user info by key.
* @param _type uint8 The info type (0: detail, 1: brief).
* @param _key string The key of user.
* @return The error code and the JSON data of user info.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function userGetByKey(uint8 _type, string _key) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (int, string) {
return InsuranceUser(userAddr_).getByKey(_type, _key);
}
/** @dev Get user policies by key.
* @param _userKey string The key of user.
* @return Error code and user policies info for JSON data.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function userGetPolicies(string _userKey) external view whenNotPaused _onlyReaderOrHigher returns (int, string) {
// check param
if (0 == bytes(_userKey).length) {
return (-1, "");
}
uint sum = policyKeys_[_userKey].sum_;
if (0 == sum) {
return (-2, "");
}
string memory str = "";
for (uint i=1; i<=sum; i++) {
str = str.concat(policyKeys_[_userKey].strs_[i]);
if (sum > i) {
str = str.concat(",");
}
}
return (0, str);
}
/** @dev Add policy.
* @param _userKey string The key of user.
* @param _templateKey string The key of policy template.
* @param _policyKey string The key of policy.
* @param _data string The JSON data of policy.
* @param _time uint The trace time(UTC), including TZ and DST.
*/
function policyAdd(string _userKey, string _templateKey, string _policyKey, string _data, uint _time) external whenNotPaused _onlyAdminOrHigher _checkPolicyAddr _checkIntegralAddr {
// check param
require(0 != bytes(_userKey).length);
require(0 != bytes(_templateKey).length);
require(0 != bytes(_policyKey).length);
require(0 != bytes(_data).length);
string memory template = "";
int error = 0;
(error, template) = InsuranceTemplate(templateAddr_).getByKey(_templateKey);
require(0 == error);
string memory policyKey = _policyKey.concat("_", maxIds_[_policyKey].toString());
InsurancePolicy(policyAddr_).add(_userKey, policyKey, template, _data);
_addPolicyKey(_userKey, policyKey);
maxIds_[_policyKey] ++;
address account = _userKey.toAddress();
if (InsuranceIntegral(integralAddr_).claim(account, 1)) {
InsuranceIntegral(integralAddr_).addTrace(account, 1, _time, InsuranceIntegral(integralAddr_).threshold(1), integralAddr_, account);
}
}
/** @dev Remove policy.
* @param _key string The key of policy.
*/
function policyRemove(string _key) external whenNotPaused _onlyOwner _checkPolicyAddr {
// check param
require(0 != bytes(_key).length);
_removePolicy(_key);
}
/** @dev Add policy's element.
* @param _key string The key of policy.
* @param _elementKey string The key of policy element.
* @param _data string The element data of policy.
*/
function policyAddElement(string _key, string _elementKey, string _data) external whenNotPaused _onlyAdminOrHigher _checkPolicyAddr {
InsurancePolicy(policyAddr_).addElement(_key, _elementKey, _data);
}
/** @dev Get policy info by key.
* @param _type uint8 The info type (0: detail, 1: brief).
* @param _key string The key of policy.
* @return The error code and the JSON data of policy info.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function policyGetByKey(uint8 _type, string _key) external view whenNotPaused _onlyReaderOrHigher _checkPolicyAddr returns (int, string) {
return InsurancePolicy(policyAddr_).getByKey(_type, _key);
}
/** @dev Get policy keys.
* @param _id uint The starting id of policy.
* @param _count uint The count wanted(include starting id).
* @return The error code and the info
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function policyGetKeys(uint _id, uint _count) external view whenNotPaused _onlyReaderOrHigher _checkPolicyAddr returns (int, string) {
return InsurancePolicy(policyAddr_).getKeys(_id, _count);
}
/** @dev Claim integrals.
* @param _account address The address that will claim the integrals.
* @param _scene uint8 The types of bonus integrals.
* 0: User sign up.
* 1: User submit data.
* 2: User check in every day.
* 3: User invite others.
* 4: User share to Wechat.
* 5: User share to QQ.
* 6: User share to Microblog.
* 7: User click advertisements.
* 8: Administrator award.
* 9: Integrals spent.
* 10: Integrals transfer to someone.
* 11: Integrals transfer from someone.
* @param _time uint The trace time(UTC), including TZ and DST.
* @param _type uint8 The types of bonus integrals.
* 0: User sign up.
* 1: User submit data.
* 2: User check in every day.
* 3: User invite others.
* 4: User share to Wechat.
* 5: User share to QQ.
* 6: User share to Microblog.
* 7: User click advertisements.
*/
function integralClaim(address _account, uint8 _scene, uint _time, uint8 _type) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _account));
if (InsuranceIntegral(integralAddr_).claim(_account, _type)) {
InsuranceIntegral(integralAddr_).addTrace(_account, _scene, _time, InsuranceIntegral(integralAddr_).threshold(_type), integralAddr_, _account);
}
}
/** @dev Burns a specific amount of integrals.
* @param _account address The account whose integrals will be burnt.
* @param _time uint The trace time(UTC), including TZ and DST.
* @param _value uint The amount of integral to be burned.
*/
function integralBurn(address _account, uint _time, uint _value) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _account));
InsuranceIntegral(integralAddr_).burn(_account, _value);
InsuranceIntegral(integralAddr_).addTrace(_account, 9, _time, _value, _account, integralAddr_);
}
/** @dev Transfer integral to a specified address
* @param _owner address The address which owns the integrals.
* @param _to address The address to transfer to.
* @param _time uint The trace time(UTC), including TZ and DST.
* @param _value uint The amount to be transferred.
*/
function integralTransfer(address _owner, address _to, uint _time, uint _value) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _owner));
require(InsuranceUser(userAddr_).exist(1, "", _to));
require(InsuranceIntegral(integralAddr_).transfer(_owner, _to, _value));
// sender
InsuranceIntegral(integralAddr_).addTrace(_owner, 10, _time, _value, _owner, _to);
// receiver
InsuranceIntegral(integralAddr_).addTrace(_to, 11, _time, _value, _owner, _to);
}
/** @dev Get trace.
* @param _account address The account whose integrals will be traced.
* @param _startTime uint The start time of trace(UTC), including TZ and DST.
* @param _endTime uint The end time of trace(UTC), including TZ and DST.
*/
function integralTrace(address _account, uint _startTime, uint _endTime) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr _checkIntegralAddr returns (string) {
require(InsuranceUser(userAddr_).exist(1, "", _account));
return InsuranceIntegral(integralAddr_).trace(_account, _startTime, _endTime);
}
/** @dev Gets the balance of the specified address.
* @param _owner address The address to query the balance of.
* @return A uint representing the amount owned by the passed address.
*/
function integralBalanceOf(address _owner) external view whenNotPaused _onlyReaderOrHigher _checkIntegralAddr returns (uint) {
return InsuranceIntegral(integralAddr_).balanceOf(_owner);
}
/** @dev Get contract related address.
* @return The addresses of contract related.
*/
function getAddr() external view whenNotPaused _onlyOwner returns (address, address, address, address, address) {
return (companyAddr_, templateAddr_, userAddr_, policyAddr_, integralAddr_);
}
}
| called by the owner to pause, triggers stopped state/ | function pause() public whenNotPaused _onlyOwner {
super.pause();
}
| 1,811,869 |
// Dependency file: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// Dependency file: contracts/access/OperatorAccess.sol
// pragma solidity >=0.8.0 <1.0.0;
// import "/mnt/c/Users/chickenhat/Desktop/chics/node_modules/@openzeppelin/contracts/access/Ownable.sol";
contract OperatorAccess is Ownable {
mapping(address => bool) public operators;
event SetOperator(address account, bool status);
function setOperator(address _account, bool _status) external onlyOwner {
operators[_account] = _status;
emit SetOperator(_account, _status);
}
modifier onlyOperator() {
require(operators[msg.sender], "only operator");
_;
}
}
// Dependency file: @openzeppelin/contracts/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);
}
// Dependency file: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
// import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// Root file: contracts/ChicCBToken.sol
pragma solidity >=0.8.0 <1.0.0;
// import "contracts/access/OperatorAccess.sol";
// import { ERC20 } from "/mnt/c/Users/chickenhat/Desktop/chics/node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ChicCBToken is ERC20("Chic Cow & Bulls Token", "MILK"), OperatorAccess {
constructor(address _teamWallet) {
uint256 premint = 1_000_000e18;
_mint(_teamWallet, premint); // 1M MILKs to team
}
/// @dev Mint token `_amount` `_to` account.
function mint(address _to, uint256 _amount) external onlyOperator {
_mint(_to, _amount);
}
/// @dev Burn token `_amount` `_from` account.
function burn(uint256 _amount) external onlyOperator {
_burn(msg.sender, _amount);
}
} | Mint token `_amount` `_to` account. | function mint(address _to, uint256 _amount) external onlyOperator {
_mint(_to, _amount);
}
| 6,160,321 |
./partial_match/4/0xc9AF60C7634D9A0BAE4b20ab042054f4C4e2AfAa/sources/DeedBoxToken.sol | Returns the _standard of the token | function standard() public view returns (string) {
return _standard;
}
| 8,509,591 |
pragma solidity ^0.5.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
//_transferOwnership(newOwner);
_pendingowner = newOwner;
emit OwnershipTransferPending(_owner, newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
address private _pendingowner;
event OwnershipTransferPending(address indexed previousOwner, address indexed newOwner);
function pendingowner() public view returns (address) {
return _pendingowner;
}
modifier onlyPendingOwner() {
require(msg.sender == _pendingowner, "Ownable: caller is not the pending owner");
_;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(msg.sender);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused, "Pausable: not paused");
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract ERC20Token is IERC20, Pausable {
using SafeMath for uint256;
using Address for address;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = totalSupply;
_balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256 balance) {
return _balances[account];
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address recipient, uint256 amount)
public
whenNotPaused
returns (bool success)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 value)
public
whenNotPaused
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount)
public
whenNotPaused
returns (bool)
{
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
whenNotPaused
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenNotPaused
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
// function mint(address account,uint256 amount) public onlyOwner returns (bool) {
// _mint(account, amount);
// 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) public onlyOwner returns (bool) {
_burn(account, amount);
return true;
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn to the zero address");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
contract BigK is ERC20Token {
constructor() public
ERC20Token("BigK", "BIGK", 18, 2100000000 * (10 ** 18)) {
}
mapping (address => uint256) internal _locked_balances;
event TokenLocked(address indexed owner, uint256 value);
event TokenUnlocked(address indexed beneficiary, uint256 value);
function balanceOfLocked(address account) public view returns (uint256 balance)
{
return _locked_balances[account];
}
function lockToken(address[] memory addresses, uint256[] memory amounts)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "LockToken: address is empty");
require(addresses.length == amounts.length, "LockToken: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_lock_token(addresses[i], amounts[i]);
}
return true;
}
function lockTokenWhole(address[] memory addresses)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "LockToken: address is empty");
for (uint i = 0; i < addresses.length; i++) {
_lock_token(addresses[i], _balances[addresses[i]]);
}
return true;
}
function unlockToken(address[] memory addresses, uint256[] memory amounts)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "LockToken: unlock address is empty");
require(addresses.length == amounts.length, "LockToken: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_unlock_token(addresses[i], amounts[i]);
}
return true;
}
function _lock_token(address owner, uint256 amount) internal {
require(owner != address(0), "LockToken: lock from the zero address");
require(amount > 0, "LockToken: the amount is empty");
_balances[owner] = _balances[owner].sub(amount);
_locked_balances[owner] = _locked_balances[owner].add(amount);
emit TokenLocked(owner, amount);
}
function _unlock_token(address owner, uint256 amount) internal {
require(owner != address(0), "LockToken: lock from the zero address");
require(amount > 0, "LockToken: the amount is empty");
_locked_balances[owner] = _locked_balances[owner].sub(amount);
_balances[owner] = _balances[owner].add(amount);
emit TokenUnlocked(owner, amount);
}
event Collect(address indexed from, address indexed to, uint256 value);
event CollectLocked(address indexed from, address indexed to, uint256 value); //Lock이 해지 되었다.
function collectFrom(address[] memory addresses, uint256[] memory amounts, address recipient)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "Collect: collect address is empty");
require(addresses.length == amounts.length, "Collect: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_transfer(addresses[i], recipient, amounts[i]);
emit Collect(addresses[i], recipient, amounts[i]);
}
return true;
}
function collectFromLocked(address[] memory addresses, uint256[] memory amounts, address recipient)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "Collect: collect address is empty");
require(addresses.length == amounts.length, "Collect: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_unlock_token(addresses[i], amounts[i]);
_transfer(addresses[i], recipient, amounts[i]);
emit CollectLocked(addresses[i], recipient, amounts[i]);
}
return true;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
} | _transferOwnership(newOwner); | function transferOwnership(address newOwner) public onlyOwner {
_pendingowner = newOwner;
emit OwnershipTransferPending(_owner, newOwner);
}
| 249,078 |
pragma solidity ^0.4.4;
contract Escrow {
struct Claim {
address sender;
uint amount;
string textHash;
string fileHash;
uint numApprovals;
}
struct InsuranceGroup {
mapping (address => bool) registeredUsers;
mapping (address => bool) paidUsers;
address[] users; uint lastUpdatedTime;
uint requiredMonthlyPayment;
uint totalAmountWithdrawn;
uint groupBalance;
}
InsuranceGroup[] groups;
mapping (address => uint) investorBalances;
address[] investors;
mapping (uint => Claim[]) claims;
// fire events for front-end whenever something is done
event LogRegistration(uint groupIndex, address sender);
event LogDeregistration(uint groupIndex, address user);
event LogPaidPremium(uint groupIndex, uint premium, address user);
event LogWithdrawal(uint groupIndex, address receiver, uint amount);
event LogCreation(uint groupIndex);
event LogUpdate(uint groupIndex);
event LogSubmitClaim(address user, uint groupIndex, string textHash, string fileHash);
event LogRegisterInvestor(address investor, uint amount);
event LogWithdrawInvestor(address investor, uint amount);
event LogInvestorAddBalance(address investor, uint amount);
event LogApprovedClaim(address investor, uint claimGroup, uint claimIndex);
function registerForGroup(uint groupIndex) payable {
// require a 1 ether deposit for this to work properly
require(msg.value == 1 ether);
groups[groupIndex].users.push(msg.sender);
groups[groupIndex].registeredUsers[msg.sender] = true;
groups[groupIndex].paidUsers[msg.sender] = false; // don't let them withdraw until premium has been paid
groups[groupIndex].groupBalance += msg.value;
LogRegistration(groupIndex, msg.sender);
updateMonthly(groupIndex);
}
function deregisterForGroup(uint groupIndex) {
// make sure the user is actually registered to the group; don't transfer to anyone
require(groups[groupIndex].registeredUsers[msg.sender]);
// remove the user from mappings
delete(groups[groupIndex].registeredUsers[msg.sender]);
delete(groups[groupIndex].paidUsers[msg.sender]);
// return their deposit back
groups[groupIndex].groupBalance -= 1 ether;
msg.sender.transfer(1 ether);
LogDeregistration(groupIndex, msg.sender);
}
function payPremium(uint groupIndex) payable {
// require the premium to be exactly equal to the monthy premium for the group
require(groups[groupIndex].requiredMonthlyPayment <= msg.value);
// make sure the user isn't paying the premium twice
require(groups[groupIndex].paidUsers[msg.sender] == false);
// set payment to true
groups[groupIndex].paidUsers[msg.sender] = true;
groups[groupIndex].groupBalance += msg.value;
LogPaidPremium(groupIndex, groups[groupIndex].requiredMonthlyPayment, msg.sender);
updateMonthly(groupIndex);
}
function getGroupBalance(uint groupIndex) constant returns (uint) {
return groups[groupIndex].groupBalance;
}
function getContractBalance() constant returns (uint) {
return this.balance;
}
function getMonthlyPremiumAmount(uint groupIndex) constant returns (uint) {
return groups[groupIndex].requiredMonthlyPayment;
}
function withdraw(uint groupIndex, uint amount) {
// verify the user
require(groups[groupIndex].registeredUsers[msg.sender]);
require(groups[groupIndex].paidUsers[msg.sender]);
require(amount < groups[groupIndex].groupBalance);
msg.sender.transfer(amount);
groups[groupIndex].groupBalance -= amount;
LogWithdrawal(groupIndex, msg.sender, amount);
}
function updateMonthly(uint groupIndex) internal {
if (now - 30 days >= groups[groupIndex].lastUpdatedTime) {
groups[groupIndex].lastUpdatedTime = now;
// reset paidUsers mapping to false
for (uint i = 0; i < groups[groupIndex].users.length; i++) {
groups[groupIndex].paidUsers[groups[groupIndex].users[i]] = false;
}
groups[groupIndex].requiredMonthlyPayment = (groups[groupIndex].totalAmountWithdrawn * 101153145236) / 10000000000;
groups[groupIndex].totalAmountWithdrawn = 0; // reset amount withdrawn for the month
}
}
function totalBalanceForGroup(uint groupIndex) constant returns (uint) {
return groups[groupIndex].groupBalance;
}
// for testing only
function forceUpdate(uint groupIndex) {
groups[groupIndex].lastUpdatedTime = now;
// reset paidUsers mapping to false
for (uint i = 0; i < groups[groupIndex].users.length; i++) {
groups[groupIndex].paidUsers[groups[groupIndex].users[i]] = false;
}
groups[groupIndex].requiredMonthlyPayment = (groups[groupIndex].totalAmountWithdrawn * 101153145236) / 10000000000;
groups[groupIndex].totalAmountWithdrawn = 0; // reset amount withdrawn for the month
LogUpdate(groupIndex);
}
function insuranceGroupCount() constant returns (uint) {
return groups.length;
}
function checkPaidUserForGroup(uint _groupIndex) constant returns (bool) {
return groups[_groupIndex].paidUsers[msg.sender];
}
function createInsuranceGroup() payable {
require(msg.value >= 2 ether);
InsuranceGroup memory group;
group.lastUpdatedTime = now;
group.groupBalance = 2 ether;
groups.push(group);
LogCreation(groups.length);
}
function numUsersInGroup(uint groupIndex) constant returns (uint) {
return groups[groupIndex].users.length;
}
function userInGroup(uint groupIndex, uint userIndex) constant returns (address) {
return groups[groupIndex].users[userIndex];
}
// MARK: INVESTORS
function registerAsInvestor() payable {
require(msg.value >= 10 ether);
investorBalances[msg.sender] = msg.value;
investors.push(msg.sender);
LogRegisterInvestor(msg.sender, msg.value);
}
function addBalanceAsInvestor() payable {
// first check that the person calling the code is an investor
bool isInvestor = false;
for (uint i = 0; i < investors.length; i++) {
if (investors[i] == msg.sender) {
isInvestor = true;
}
}
require(isInvestor);
investorBalances[msg.sender] += msg.value;
LogInvestorAddBalance(msg.sender, msg.value);
}
function withdrawAsInvestor(uint _amount) {
require(_amount <= investorBalances[msg.sender]);
msg.sender.transfer(_amount);
LogWithdrawInvestor(msg.sender, _amount);
}
function getInvestorBalance() constant returns (uint) {
return investorBalances[msg.sender];
}
function approveClaim(uint _groupIndex, uint _claimId) {
// only investors with a certain stake in the network can approve claims; i.e. more than 10 ether
// first check that the person calling the code is an investor
bool isInvestor = false;
for (uint i = 0; i < investors.length; i++) {
if (investors[i] == msg.sender) {
isInvestor = true;
}
}
if (!isInvestor) revert();
// now check the investor's stake
require(investorBalances[msg.sender] >= 10 ether);
// everything passes; approve the claim
claims[_groupIndex][_claimId].numApprovals += 1;
LogApprovedClaim(msg.sender, _groupIndex, _claimId);
if (claims[_groupIndex][_claimId].numApprovals == 1) {
// first approval: transfer balance
claims[_groupIndex][_claimId].sender.transfer(claims[_groupIndex][_claimId].amount);
}
}
// MARK: CLAIMS
function submitClaim(uint _groupIndex, uint _requestedAmount, string _textHash, string _fileHash) {
// TODO: check that the msg.sender is in fact a paying user in the group
Claim memory c;
c.sender = msg.sender;
c.amount = _requestedAmount;
c.textHash = _textHash;
c.fileHash = _fileHash;
claims[_groupIndex].push(c);
LogSubmitClaim(msg.sender, _groupIndex, _textHash, _fileHash);
}
function numClaimsInGroup(uint _groupIndex) constant returns (uint) {
return claims[_groupIndex].length;
}
function fetchClaimFromGroupByIndex(uint _groupIndex, uint _claimIndex) constant returns (address, uint, string, string) {
Claim memory c = claims[_groupIndex][_claimIndex];
return (c.sender, c.amount, c.textHash, c.fileHash);
}
// DEBUG functions
function numPayingUsersInGroup(uint groupIndex) constant returns (uint) {
uint result = 0;
for (uint i = 0; i < groups[groupIndex].users.length; i++) {
if (groups[groupIndex].paidUsers[groups[groupIndex].users[i]]) {
result += 1;
}
}
return result;
}
}
| require a 1 ether deposit for this to work properly | function registerForGroup(uint groupIndex) payable {
require(msg.value == 1 ether);
groups[groupIndex].users.push(msg.sender);
groups[groupIndex].registeredUsers[msg.sender] = true;
groups[groupIndex].groupBalance += msg.value;
LogRegistration(groupIndex, msg.sender);
updateMonthly(groupIndex);
}
| 12,748,304 |
./full_match/82/0x084c77e84853B960aEB0a0BD4Fc6689aC9c6d76E/sources/Storage.sol | Store value in variable num value to store/ | function store(uint256 num) public {
number = num;
}
| 7,093,451 |
./full_match/1/0x36d4686e19c052787D7f24E6913cEbC025714895/sources/contracts/OFTWrapper.sol | approve proxy to spend tokens | function sendProxyOFT(
address _proxyOft,
uint16 _dstChainId,
bytes calldata _toAddress,
uint256 _amount,
uint256 _minAmount,
address payable _refundAddress,
address _zroPaymentAddress,
bytes calldata _adapterParams,
FeeObj calldata _feeObj
) external payable nonReentrant {
address token = IOFTV2(_proxyOft).token();
{
uint256 amountToSwap = _getAmountAndPayFeeProxy(token, _amount, _minAmount, _feeObj);
IOFT(token).safeApprove(_proxyOft, amountToSwap);
}
}
| 2,981,411 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
pragma experimental ABIEncoderV2;
import "./Pairing.sol";
/// @title Public Compact Proof of Retrievability Implemantion
/// @notice This smart contract is developed for testing purpose only.
/// There are no rule implemented in this version to secure the
/// protocol between the client and the server.
/// Read Compact Proofs of Retrievability for more information.
/// @author Lucas GICQUEL
contract Compact {
// to control access to specific functions, I store the server address
address server;
// client metadata used to verify each proof
Pairing.G2Point public_key;
Pairing.G1Point[] u;
uint name;
uint file_size;
/**
* A challenge, sent by anyone but the server, is defined by two list of
* integers:
* - i: i-th bit of file to challenge (0 <= i < file_size)
* - nu: independant factor chosen by the client, making each
* challenge unique and unpredictable
*/
struct Challenge {
uint[] i;
uint[] nu;
}
/**
* Proof calculated by the server, it mathematically proves that she truly
* store the file.
* Valid state is true if the proof is valid, false otherwise.
*/
struct Proof {
uint[] mu;
Pairing.G1Point sigma;
bool valid;
}
/**
* To store and facilitate information retrieval
*/
uint[] challenges;
mapping(uint => Challenge) index_challenges;
uint[] proofs;
mapping(uint => Proof) index_proofs;
/// @notice Called by a client when she wants to store her file in a
/// distant server.
/// She sends all metadata in this part allowing the smart contract
/// to verify the proofs calculated by the server.
/// @param _pk_x abscissa of the public key
/// @param _pk_y ordinate of the public key
/// @param _u_x list of abscissas of points u used both to sign and verify
/// @param _u_y list of ordinates of points u used both to sign and verify
/// @param _name integer used as file identifier
/// @param _file_size size of the original in bytes
constructor(
address _server,
uint[2] memory _pk_x,
uint[2] memory _pk_y,
uint[] memory _u_x,
uint[] memory _u_y,
uint _name,
uint _file_size
)
public
{
if (_file_size == 0) {
revert("File size must be superior to 0");
}
if (_server == address(0) || _server == msg.sender) {
revert("Server address invalid.");
}
if (_u_x.length != _u_y.length) {
revert("To create points, we need as many x as y");
}
server = _server;
public_key = Pairing.G2Point(_pk_x, _pk_y);
for(uint i = 0; i < _u_x.length; i++){
u.push(Pairing.G1Point(_u_x[i], _u_y[i]));
}
name = _name;
file_size = _file_size;
}
/// @notice Anybody but the server calls this function in order to submit a
/// new challenge to server. Therefore, the server must answer this
/// challenge by a corresponding proof.
/// Adds the given challenge into the Challenge list.
/// @param _i list that indicates the i-th bit of the original file to
/// challenge
/// @param _nu list of factors chosen by the client making challenges
/// unpredictable
function challenge(uint[] memory _i, uint[] memory _nu) public {
if (msg.sender == server) {
revert("The server is not able to call this function");
}
if (_i.length != _nu.length) {
revert("Each i-th bit need a factor nu to compute the proof");
}
uint id = challenges.push(challenges.length);
// i must NOT be superior to the number of signatures
// number of signatures = file size / u.length
for(uint j = 0; j < _i.length; j++) {
index_challenges[id].i.push(_i[j] % (file_size/u.length));
index_challenges[id].nu.push(_nu[j]);
}
}
/// @notice Mathematical answer to the last challenge sent.
/// This function can only be called by the server.
/// @param _mu First part of the proof (list)
/// @param _sigma_x Abscissa of the second part of the proof
/// @param _sigma_y Ordinate of the second part of the proof
function proof(uint[] memory _mu, uint _sigma_x, uint _sigma_y) public {
if (msg.sender != server) {
revert("Only the server can call this function");
}
uint id = proofs.push(proofs.length);
// i must NOT be superior to the file size
index_proofs[id] = Proof(_mu, Pairing.G1Point(_sigma_x, _sigma_y), false);
verify();
}
/// @notice Verifies if the proof sent by the server is valid according to
/// the last challenge sent by the client.
/// The valid statement will be updated depending on the
/// correctness of the proof.
/// Internal function, automatically called after the proof is sent
function verify() internal {
Proof storage p = index_proofs[proofs.length];
Challenge memory c = index_challenges[challenges.length];
Pairing.G1Point memory h;
Pairing.G1Point memory res_h;
Pairing.G1Point memory res_u;
Pairing.G1Point memory res;
for (uint j = 0; j < c.i.length; j++) {
h = Pairing.curveMul(Pairing.P1(), (name * c.i[j]));
h = Pairing.curveMul(h, c.nu[j]);
res_h = Pairing.addition(res_h, h);
}
for (uint j = 0; j < u.length; j++) {
res_u = Pairing.curveMul(u[j], p.mu[j]);
res = Pairing.addition(res, res_u);
}
res = Pairing.addition(res, res_h);
p.valid =
Pairing.pairing2(
Pairing.negate(p.sigma),
Pairing.P2(),
res,
public_key
);
}
/// @notice gets the challenge with the identifier given in parameter
/// @param _id identifier of the challenge to return
/// @return the challenge with the identifier <id>
function getChallenge(uint _id) public view returns(Challenge memory) {
return index_challenges[_id];
}
/// @notice gets the proof with the identifier given in parameter
/// @param _id identifier of the proof to return
/// @return the proof with identifier <id>
function getProof(uint _id) public view returns(Proof memory) {
return index_proofs[_id];
}
/// @notice gets the number of all challenges sent
/// @return the number of all challenges sent
function getChallengesLength() public view returns(uint) {
return challenges.length;
}
/// @notice gets the number of all proofs sent
/// @return the number of all proofs sent
function getProofsLength() public view returns(uint) {
return proofs.length;
}
} | gets the proof with the identifier given in parameter _id identifier of the proof to return return the proof with identifier <id> | function getProof(uint _id) public view returns(Proof memory) {
return index_proofs[_id];
}
| 12,755,255 |
// Sources flattened with hardhat v2.0.8 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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 @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, basic interface
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is 0x80ac58cd.
*/
interface IERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* Gets the balance of the specified address
* @param owner address to query the balance of
* @return balance uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* Gets the owner of the specified ID
* @param tokenId uint256 ID to query the owner of
* @return owner address currently marked as the owner of the given ID
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) external;
/**
* Gets the approved address for a token ID, or zero if no address set
* @dev Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return operator address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* Safely transfers the ownership of a given token ID to another address
*
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* Safely transfers the ownership of a given token ID to another address
*
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is 0x5b5e139f.
*/
interface IERC721Metadata {
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory);
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory);
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
* @return string URI of given token ID
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC721 Non-Fungible Token Standard, optional unsafe batchTransfer interface
* @dev See https://eips.ethereum.org/EIPS/eip-721
* Note: The ERC-165 identifier for this interface is.
*/
interface IERC721BatchTransfer {
/**
* Unsafely transfers a batch of tokens.
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `tokenIds` is not owned by `from`.
* @dev Resets the token approval for each of `tokenIds`.
* @dev Emits an {IERC721-Transfer} event for each of `tokenIds`.
* @param from Current tokens owner.
* @param to Address of the new token owner.
* @param tokenIds Identifiers of the tokens to transfer.
*/
function batchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC721/[email protected]
pragma solidity 0.6.8;
/**
@title ERC721 Non-Fungible Token Standard, token receiver
@dev See https://eips.ethereum.org/EIPS/eip-721
Interface for any contract that wants to support safeTransfers from ERC721 asset contracts.
Note: The ERC-165 identifier for this interface is 0x150b7a02.
*/
interface IERC721Receiver {
/**
@notice Handle the receipt of an NFT
@dev The ERC721 smart contract calls this function on the recipient
after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
otherwise the caller will revert the transaction. The selector to be
returned can be obtained as `this.onERC721Received.selector`. This
function MAY throw to revert and reject the transfer.
Note: the ERC721 contract address is always the message sender.
@param operator The address which called `safeTransferFrom` function
@param from The address which previously owned the token
@param tokenId The NFT identifier which is being transferred
@param data Additional data with no specified format
@return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/introspection/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, basic interface
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
interface IERC1155 {
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 _owner, address indexed _operator, bool _approved);
event URI(string _value, uint256 indexed _id);
/**
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Emits a `TransferSingle` event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to send along to a receiver contract.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
/**
* Safely transfers a batch of tokens.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `from` has an insufficient balance for any of `ids`.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits a `TransferBatch` event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to send along to a receiver contract.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
/**
* Retrieves the balance of `id` owned by account `owner`.
* @param owner The account to retrieve the balance of.
* @param id The identifier to retrieve the balance of.
* @return The balance of `id` owned by account `owner`.
*/
function balanceOf(address owner, uint256 id) external view returns (uint256);
/**
* Retrieves the balances of `ids` owned by accounts `owners`. For each pair:
* @dev Reverts if `owners` and `ids` have different lengths.
* @param owners The addresses of the token holders
* @param ids The identifiers to retrieve the balance of.
* @return The balances of `ids` owned by accounts `owners`.
*/
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* Enables or disables an operator's approval.
* @dev Emits an `ApprovalForAll` event.
* @param operator Address of the operator.
* @param approved True to approve the operator, false to revoke an approval.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* Retrieves the approval status of an operator for a given owner.
* @param owner Address of the authorisation giver.
* @param operator Address of the operator.
* @return True if the operator is approved, false if not.
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, optional metadata URI extension
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Note: The ERC-165 identifier for this interface is 0x0e89341c.
*/
interface IERC1155MetadataURI {
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* @dev The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
* @dev The uri function SHOULD be used to retrieve values if no event was emitted.
* @dev The uri function MUST return the same value as the latest event for an _id if it was emitted.
* @dev The uri function MUST NOT be used to check for the existence of a token as it is possible for
* an implementation to return a valid string even if the token does not exist.
* @return URI string
*/
function uri(uint256 id) external view returns (string memory);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, optional Inventory extension
* @dev See https://eips.ethereum.org/EIPS/eip-xxxx
* Interface for fungible/non-fungible tokens management on a 1155-compliant contract.
*
* This interface rationalizes the co-existence of fungible and non-fungible tokens
* within the same contract. As several kinds of fungible tokens can be managed under
* the Multi-Token standard, we consider that non-fungible tokens can be classified
* under their own specific type. We introduce the concept of non-fungible collection
* and consider the usage of 3 types of identifiers:
* (a) Fungible Token identifiers, each representing a set of Fungible Tokens,
* (b) Non-Fungible Collection identifiers, each representing a set of Non-Fungible Tokens (this is not a token),
* (c) Non-Fungible Token identifiers.
* Identifiers nature
* | Type | isFungible | isCollection | isToken |
* | Fungible Token | true | true | true |
* | Non-Fungible Collection | false | true | false |
* | Non-Fungible Token | false | false | true |
*
* Identifiers compatibilities
* | Type | transfer | balance | supply | owner |
* | Fungible Token | OK | OK | OK | NOK |
* | Non-Fungible Collection | NOK | OK | OK | NOK |
* | Non-Fungible Token | OK | 0 or 1 | 0 or 1 | OK |
*
* Note: The ERC-165 identifier for this interface is 0x469bd23f.
*/
interface IERC1155Inventory {
/**
* Optional event emitted when a collection (Fungible Token or Non-Fungible Collection) is created.
* This event can be used by a client application to determine which identifiers are meaningful
* to track through the functions `balanceOf`, `balanceOfBatch` and `totalSupply`.
* @dev This event MUST NOT be emitted twice for the same `collectionId`.
*/
event CollectionCreated(uint256 indexed collectionId, bool indexed fungible);
/**
* Retrieves the owner of a non-fungible token (ERC721-compatible).
* @dev Reverts if `nftId` is owned by the zero address.
* @param nftId Identifier of the token to query.
* @return Address of the current owner of the token.
*/
function ownerOf(uint256 nftId) external view returns (address);
/**
* Introspects whether or not `id` represents a fungible token.
* This function MUST return true even for a fungible token which is not-yet created.
* @param id The identifier to query.
* @return bool True if `id` represents afungible token, false otherwise.
*/
function isFungible(uint256 id) external pure returns (bool);
/**
* Introspects the non-fungible collection to which `nftId` belongs.
* @dev This function MUST return a value representing a non-fungible collection.
* @dev This function MUST return a value for a non-existing token, and SHOULD NOT be used to check the existence of a non-fungible token.
* @dev Reverts if `nftId` does not represent a non-fungible token.
* @param nftId The token identifier to query the collection of.
* @return The non-fungible collection identifier to which `nftId` belongs.
*/
function collectionOf(uint256 nftId) external pure returns (uint256);
/**
* Retrieves the total supply of `id`.
* @param id The identifier for which to retrieve the supply of.
* @return
* If `id` represents a collection (fungible token or non-fungible collection), the total supply for this collection.
* If `id` represents a non-fungible token, 1 if the token exists, else 0.
*/
function totalSupply(uint256 id) external view returns (uint256);
/**
* @notice this documentation overrides {IERC1155-balanceOf(address,uint256)}.
* Retrieves the balance of `id` owned by account `owner`.
* @param owner The account to retrieve the balance of.
* @param id The identifier to retrieve the balance of.
* @return
* If `id` represents a collection (fungible token or non-fungible collection), the balance for this collection.
* If `id` represents a non-fungible token, 1 if the token is owned by `owner`, else 0.
*/
// function balanceOf(address owner, uint256 id) external view returns (uint256);
/**
* @notice this documentation overrides {IERC1155-balanceOfBatch(address[],uint256[])}.
* Retrieves the balances of `ids` owned by accounts `owners`.
* @dev Reverts if `owners` and `ids` have different lengths.
* @param owners The accounts to retrieve the balances of.
* @param ids The identifiers to retrieve the balances of.
* @return An array of elements such as for each pair `id`/`owner`:
* If `id` represents a collection (fungible token or non-fungible collection), the balance for this collection.
* If `id` represents a non-fungible token, 1 if the token is owned by `owner`, else 0.
*/
// function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @notice this documentation overrides its {IERC1155-safeTransferFrom(address,address,uint256,uint256,bytes)}.
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `id` does not represent a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 id,
// uint256 value,
// bytes calldata data
// ) external;
/**
* @notice this documentation overrides its {IERC1155-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
* Safely transfers a batch of tokens.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `ids` does not represent a token.
* @dev Reverts if one of `ids` represents a non-fungible token and `value` is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if one of `ids` represents a fungible token and `value` is 0.
* @dev Reverts if one of `ids` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if one of `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits an {IERC1155-TransferBatch} event.
* @param from Current tokens owner.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeBatchTransferFrom(
// address from,
// address to,
// uint256[] calldata ids,
// uint256[] calldata values,
// bytes calldata data
// ) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Multi Token Standard, token receiver
* @dev See https://eips.ethereum.org/EIPS/eip-1155
* Interface for any contract that wants to support transfers from ERC1155 asset contracts.
* Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type.
* An ERC1155 contract MUST call this function on a recipient contract, at the end of a `safeTransferFrom` after the balance update.
* This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61) to accept the transfer.
* Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types.
* An ERC1155 contract MUST call this function on a recipient contract, at the end of a `safeBatchTransferFrom` after the balance updates.
* This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81) if to accept the transfer(s).
* Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match _values array)
* @param values An array containing amounts of each token being transferred (order and length must match _ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC1155InventoryIdentifiersLib, a library to introspect inventory identifiers.
* @dev With N=32, representing the Non-Fungible Collection mask length, identifiers are represented as follow:
* (a) a Fungible Token:
* - most significant bit == 0
* (b) a Non-Fungible Collection:
* - most significant bit == 1
* - (256-N) least significant bits == 0
* (c) a Non-Fungible Token:
* - most significant bit == 1
* - (256-N) least significant bits != 0
*/
library ERC1155InventoryIdentifiersLib {
// Non-fungible bit. If an id has this bit set, it is a non-fungible (either collection or token)
uint256 internal constant _NF_BIT = 1 << 255;
// Mask for non-fungible collection (including the nf bit)
uint256 internal constant _NF_COLLECTION_MASK = uint256(type(uint32).max) << 224;
uint256 internal constant _NF_TOKEN_MASK = ~_NF_COLLECTION_MASK;
function isFungibleToken(uint256 id) internal pure returns (bool) {
return id & _NF_BIT == 0;
}
function isNonFungibleToken(uint256 id) internal pure returns (bool) {
return id & _NF_BIT != 0 && id & _NF_TOKEN_MASK != 0;
}
function getNonFungibleCollection(uint256 nftId) internal pure returns (uint256) {
return nftId & _NF_COLLECTION_MASK;
}
}
abstract contract ERC1155InventoryBase is IERC1155, IERC1155MetadataURI, IERC1155Inventory, IERC165, Context {
using ERC1155InventoryIdentifiersLib for uint256;
bytes4 private constant _ERC165_INTERFACE_ID = type(IERC165).interfaceId;
bytes4 private constant _ERC1155_INTERFACE_ID = type(IERC1155).interfaceId;
bytes4 private constant _ERC1155_METADATA_URI_INTERFACE_ID = type(IERC1155MetadataURI).interfaceId;
bytes4 private constant _ERC1155_INVENTORY_INTERFACE_ID = type(IERC1155Inventory).interfaceId;
// bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 internal constant _ERC1155_RECEIVED = 0xf23a6e61;
// bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
bytes4 internal constant _ERC1155_BATCH_RECEIVED = 0xbc197c81;
// Burnt non-fungible token owner's magic value
uint256 internal constant _BURNT_NFT_OWNER = 0xdead000000000000000000000000000000000000000000000000000000000000;
/* owner => operator => approved */
mapping(address => mapping(address => bool)) internal _operators;
/* collection ID => owner => balance */
mapping(uint256 => mapping(address => uint256)) internal _balances;
/* collection ID => supply */
mapping(uint256 => uint256) internal _supplies;
/* NFT ID => owner */
mapping(uint256 => uint256) internal _owners;
/* collection ID => creator */
mapping(uint256 => address) internal _creators;
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == _ERC165_INTERFACE_ID ||
interfaceId == _ERC1155_INTERFACE_ID ||
interfaceId == _ERC1155_METADATA_URI_INTERFACE_ID ||
interfaceId == _ERC1155_INVENTORY_INTERFACE_ID;
}
//================================== ERC1155 =======================================/
/// @dev See {IERC1155-balanceOf(address,uint256)}.
function balanceOf(address owner, uint256 id) public view virtual override returns (uint256) {
require(owner != address(0), "Inventory: zero address");
if (id.isNonFungibleToken()) {
return address(_owners[id]) == owner ? 1 : 0;
}
return _balances[id][owner];
}
/// @dev See {IERC1155-balanceOfBatch(address[],uint256[])}.
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view virtual override returns (uint256[] memory) {
require(owners.length == ids.length, "Inventory: inconsistent arrays");
uint256[] memory balances = new uint256[](owners.length);
for (uint256 i = 0; i != owners.length; ++i) {
balances[i] = balanceOf(owners[i], ids[i]);
}
return balances;
}
/// @dev See {IERC1155-setApprovalForAll(address,bool)}.
function setApprovalForAll(address operator, bool approved) public virtual override {
address sender = _msgSender();
require(operator != sender, "Inventory: self-approval");
_operators[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/// @dev See {IERC1155-isApprovedForAll(address,address)}.
function isApprovedForAll(address tokenOwner, address operator) public view virtual override returns (bool) {
return _operators[tokenOwner][operator];
}
//================================== ERC1155Inventory =======================================/
/// @dev See {IERC1155Inventory-isFungible(uint256)}.
function isFungible(uint256 id) external pure virtual override returns (bool) {
return id.isFungibleToken();
}
/// @dev See {IERC1155Inventory-collectionOf(uint256)}.
function collectionOf(uint256 nftId) external pure virtual override returns (uint256) {
require(nftId.isNonFungibleToken(), "Inventory: not an NFT");
return nftId.getNonFungibleCollection();
}
/// @dev See {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) public view virtual override returns (address) {
address owner = address(_owners[nftId]);
require(owner != address(0), "Inventory: non-existing NFT");
return owner;
}
/// @dev See {IERC1155Inventory-totalSupply(uint256)}.
function totalSupply(uint256 id) external view virtual override returns (uint256) {
if (id.isNonFungibleToken()) {
return address(_owners[id]) == address(0) ? 0 : 1;
} else {
return _supplies[id];
}
}
//================================== ABI-level Internal Functions =======================================/
/**
* Creates a collection (optional).
* @dev Reverts if `collectionId` does not represent a collection.
* @dev Reverts if `collectionId` has already been created.
* @dev Emits a {IERC1155Inventory-CollectionCreated} event.
* @param collectionId Identifier of the collection.
*/
function _createCollection(uint256 collectionId) internal virtual {
require(!collectionId.isNonFungibleToken(), "Inventory: not a collection");
require(_creators[collectionId] == address(0), "Inventory: existing collection");
_creators[collectionId] = _msgSender();
emit CollectionCreated(collectionId, collectionId.isFungibleToken());
}
/// @dev See {IERC1155InventoryCreator-creator(uint256)}.
function _creator(uint256 collectionId) internal view virtual returns (address) {
require(!collectionId.isNonFungibleToken(), "Inventory: not a collection");
return _creators[collectionId];
}
//================================== Internal Helper Functions =======================================/
/**
* Returns whether `sender` is authorised to make a transfer on behalf of `from`.
* @param from The address to check operatibility upon.
* @param sender The sender address.
* @return True if sender is `from` or an operator for `from`, false otherwise.
*/
function _isOperatable(address from, address sender) internal view virtual returns (bool) {
return (from == sender) || _operators[from][sender];
}
/**
* Calls {IERC1155TokenReceiver-onERC1155Received} on a target contract.
* @dev Reverts if `to` is not a contract.
* @dev Reverts if the call to the target fails or is refused.
* @param from Previous token owner.
* @param to New token owner.
* @param id Identifier of the token transferred.
* @param value Amount of token transferred.
* @param data Optional data to send along with the receiver contract call.
*/
function _callOnERC1155Received(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) internal {
require(IERC1155TokenReceiver(to).onERC1155Received(_msgSender(), from, id, value, data) == _ERC1155_RECEIVED, "Inventory: transfer refused");
}
/**
* Calls {IERC1155TokenReceiver-onERC1155batchReceived} on a target contract.
* @dev Reverts if `to` is not a contract.
* @dev Reverts if the call to the target fails or is refused.
* @param from Previous tokens owner.
* @param to New tokens owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to send along with the receiver contract call.
*/
function _callOnERC1155BatchReceived(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
require(
IERC1155TokenReceiver(to).onERC1155BatchReceived(_msgSender(), from, ids, values, data) == _ERC1155_BATCH_RECEIVED,
"Inventory: transfer refused"
);
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC1155721Inventory, an ERC1155Inventory with additional support for ERC721.
*/
abstract contract ERC1155721Inventory is IERC721, IERC721Metadata, IERC721BatchTransfer, ERC1155InventoryBase {
using Address for address;
bytes4 private constant _ERC165_INTERFACE_ID = type(IERC165).interfaceId;
bytes4 private constant _ERC1155_TOKEN_RECEIVER_INTERFACE_ID = type(IERC1155TokenReceiver).interfaceId;
bytes4 private constant _ERC721_INTERFACE_ID = type(IERC721).interfaceId;
bytes4 private constant _ERC721_METADATA_INTERFACE_ID = type(IERC721Metadata).interfaceId;
bytes4 internal constant _ERC721_RECEIVED = type(IERC721Receiver).interfaceId;
uint256 internal constant _APPROVAL_BIT_TOKEN_OWNER_ = 1 << 160;
/* owner => NFT balance */
mapping(address => uint256) internal _nftBalances;
/* NFT ID => operator */
mapping(uint256 => address) internal _nftApprovals;
/// @dev See {IERC165-supportsInterface(bytes4)}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || interfaceId == _ERC721_INTERFACE_ID || interfaceId == _ERC721_METADATA_INTERFACE_ID;
}
//===================================== ERC721 ==========================================/
/// @dev See {IERC721-balanceOf(address)}.
function balanceOf(address tokenOwner) external view virtual override returns (uint256) {
require(tokenOwner != address(0), "Inventory: zero address");
return _nftBalances[tokenOwner];
}
/// @dev See {IERC721-ownerOf(uint256)} and {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) public view virtual override(IERC721, ERC1155InventoryBase) returns (address) {
return ERC1155InventoryBase.ownerOf(nftId);
}
/// @dev See {IERC721-approve(address,uint256)}.
function approve(address to, uint256 nftId) external virtual override {
address tokenOwner = ownerOf(nftId);
require(to != tokenOwner, "Inventory: self-approval");
require(_isOperatable(tokenOwner, _msgSender()), "Inventory: non-approved sender");
_owners[nftId] = uint256(tokenOwner) | _APPROVAL_BIT_TOKEN_OWNER_;
_nftApprovals[nftId] = to;
emit Approval(tokenOwner, to, nftId);
}
/// @dev See {IERC721-getApproved(uint256)}.
function getApproved(uint256 nftId) external view virtual override returns (address) {
uint256 tokenOwner = _owners[nftId];
require(address(tokenOwner) != address(0), "Inventory: non-existing NFT");
if (tokenOwner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) {
return _nftApprovals[nftId];
} else {
return address(0);
}
}
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function isApprovedForAll(address tokenOwner, address operator) public view virtual override(IERC721, ERC1155InventoryBase) returns (bool) {
return ERC1155InventoryBase.isApprovedForAll(tokenOwner, operator);
}
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function setApprovalForAll(address operator, bool approved) public virtual override(IERC721, ERC1155InventoryBase) {
return ERC1155InventoryBase.setApprovalForAll(operator, approved);
}
/**
* Unsafely transfers a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721Inventory-transferFrom(address,address,uint256)}.
*/
function transferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
_transferFrom(
from,
to,
nftId,
"",
/* safe */
false
);
}
/**
* Safely transfers a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721Inventory-safeTransferFrom(address,address,uint256)}.
*/
function safeTransferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
_transferFrom(
from,
to,
nftId,
"",
/* safe */
true
);
}
/**
* Safely transfers a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721Inventory-safeTransferFrom(address,address,uint256,bytes)}.
*/
function safeTransferFrom(
address from,
address to,
uint256 nftId,
bytes memory data
) public virtual override {
_transferFrom(
from,
to,
nftId,
data,
/* safe */
true
);
}
/**
* Unsafely transfers a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721BatchTransfer-batchTransferFrom(address,address,uint256[])}.
*/
function batchTransferFrom(
address from,
address to,
uint256[] memory nftIds
) public virtual override {
require(to != address(0), "Inventory: transfer to zero");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 length = nftIds.length;
uint256[] memory values = new uint256[](length);
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 nftId = nftIds[i];
values[i] = 1;
_transferNFT(from, to, nftId, 1, operatable, true);
emit Transfer(from, to, nftId);
uint256 nextCollectionId = nftId.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
}
if (nfCollectionId != 0) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
_transferNFTUpdateBalances(from, to, length);
}
emit TransferBatch(_msgSender(), from, to, nftIds, values);
if (to.isContract() && _isERC1155TokenReceiver(to)) {
_callOnERC1155BatchReceived(from, to, nftIds, values, "");
}
}
/// @dev See {IERC721Metadata-tokenURI(uint256)}.
function tokenURI(uint256 nftId) external view virtual override returns (string memory) {
require(address(_owners[nftId]) != address(0), "Inventory: non-existing NFT");
return uri(nftId);
}
//================================== ERC1155 =======================================/
/**
* Safely transfers some token (ERC1155-compatible).
* @dev See {IERC1155721Inventory-safeTransferFrom(address,address,uint256,uint256,bytes)}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
address sender = _msgSender();
require(to != address(0), "Inventory: transfer to zero");
bool operatable = _isOperatable(from, sender);
if (id.isFungibleToken()) {
_transferFungible(from, to, id, value, operatable);
} else if (id.isNonFungibleToken()) {
_transferNFT(from, to, id, value, operatable, false);
emit Transfer(from, to, id);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, to, id, value);
if (to.isContract()) {
_callOnERC1155Received(from, to, id, value, data);
}
}
/**
* Safely transfers a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
// internal function to avoid stack too deep error
_safeBatchTransferFrom(from, to, ids, values, data);
}
//================================== ERC1155MetadataURI =======================================/
/// @dev See {IERC1155MetadataURI-uri(uint256)}.
function uri(uint256) public view virtual override returns (string memory);
//================================== ABI-level Internal Functions =======================================/
/**
* Safely or unsafely transfers some token (ERC721-compatible).
* @dev For `safe` transfer, see {IERC1155721Inventory-transferFrom(address,address,uint256)}.
* @dev For un`safe` transfer, see {IERC1155721Inventory-safeTransferFrom(address,address,uint256,bytes)}.
*/
function _transferFrom(
address from,
address to,
uint256 nftId,
bytes memory data,
bool safe
) internal {
require(to != address(0), "Inventory: transfer to zero");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
_transferNFT(from, to, nftId, 1, operatable, false);
emit Transfer(from, to, nftId);
emit TransferSingle(sender, from, to, nftId, 1);
if (to.isContract()) {
if (_isERC1155TokenReceiver(to)) {
_callOnERC1155Received(from, to, nftId, 1, data);
} else if (safe) {
_callOnERC721Received(from, to, nftId, data);
}
}
}
/**
* Safely transfers a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
require(to != address(0), "Inventory: transfer to zero");
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 nfCollectionId;
uint256 nfCollectionCount;
uint256 nftsCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
if (id.isFungibleToken()) {
_transferFungible(from, to, id, values[i], operatable);
} else if (id.isNonFungibleToken()) {
_transferNFT(from, to, id, values[i], operatable, true);
emit Transfer(from, to, id);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nftsCount += nfCollectionCount;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount);
nftsCount += nfCollectionCount;
_transferNFTUpdateBalances(from, to, nftsCount);
}
emit TransferBatch(_msgSender(), from, to, ids, values);
if (to.isContract()) {
_callOnERC1155BatchReceived(from, to, ids, values, data);
}
}
/**
* Safely or unsafely mints some token (ERC721-compatible).
* @dev For `safe` mint, see {IERC1155721InventoryMintable-mint(address,uint256)}.
* @dev For un`safe` mint, see {IERC1155721InventoryMintable-safeMint(address,uint256,bytes)}.
*/
function _mint(
address to,
uint256 nftId,
bytes memory data,
bool safe
) internal {
require(to != address(0), "Inventory: transfer to zero");
require(nftId.isNonFungibleToken(), "Inventory: not an NFT");
_mintNFT(to, nftId, 1, false);
emit Transfer(address(0), to, nftId);
emit TransferSingle(_msgSender(), address(0), to, nftId, 1);
if (to.isContract()) {
if (_isERC1155TokenReceiver(to)) {
_callOnERC1155Received(address(0), to, nftId, 1, data);
} else if (safe) {
_callOnERC721Received(address(0), to, nftId, data);
}
}
}
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256[])}.
*/
function _batchMint(address to, uint256[] memory nftIds) internal {
require(to != address(0), "Inventory: transfer to zero");
uint256 length = nftIds.length;
uint256[] memory values = new uint256[](length);
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 nftId = nftIds[i];
require(nftId.isNonFungibleToken(), "Inventory: not an NFT");
values[i] = 1;
_mintNFT(to, nftId, 1, true);
emit Transfer(address(0), to, nftId);
uint256 nextCollectionId = nftId.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
}
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
_nftBalances[to] += length;
emit TransferBatch(_msgSender(), address(0), to, nftIds, values);
if (to.isContract() && _isERC1155TokenReceiver(to)) {
_callOnERC1155BatchReceived(address(0), to, nftIds, values, "");
}
}
/**
* Safely mints some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}.
*/
function _safeMint(
address to,
uint256 id,
uint256 value,
bytes memory data
) internal virtual {
require(to != address(0), "Inventory: transfer to zero");
address sender = _msgSender();
if (id.isFungibleToken()) {
_mintFungible(to, id, value);
} else if (id.isNonFungibleToken()) {
_mintNFT(to, id, value, false);
emit Transfer(address(0), to, id);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, address(0), to, id, value);
if (to.isContract()) {
_callOnERC1155Received(address(0), to, id, value, data);
}
}
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeBatchMint(address,uint256[],uint256[],bytes)}.
*/
function _safeBatchMint(
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal virtual {
require(to != address(0), "Inventory: transfer to zero");
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
uint256 nfCollectionId;
uint256 nfCollectionCount;
uint256 nftsCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_mintFungible(to, id, value);
} else if (id.isNonFungibleToken()) {
_mintNFT(to, id, value, true);
emit Transfer(address(0), to, id);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
nfCollectionId = nextCollectionId;
nftsCount += nfCollectionCount;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][to] += nfCollectionCount;
_supplies[nfCollectionId] += nfCollectionCount;
nftsCount += nfCollectionCount;
_nftBalances[to] += nftsCount;
}
emit TransferBatch(_msgSender(), address(0), to, ids, values);
if (to.isContract()) {
_callOnERC1155BatchReceived(address(0), to, ids, values, data);
}
}
//============================== Internal Helper Functions =======================================/
function _mintFungible(
address to,
uint256 id,
uint256 value
) internal {
require(value != 0, "Inventory: zero value");
uint256 supply = _supplies[id];
uint256 newSupply = supply + value;
require(newSupply > supply, "Inventory: supply overflow");
_supplies[id] = newSupply;
// cannot overflow as supply cannot overflow
_balances[id][to] += value;
}
function _mintNFT(
address to,
uint256 id,
uint256 value,
bool isBatch
) internal {
require(value == 1, "Inventory: wrong NFT value");
require(_owners[id] == 0, "Inventory: existing/burnt NFT");
_owners[id] = uint256(to);
if (!isBatch) {
uint256 collectionId = id.getNonFungibleCollection();
// it is virtually impossible that a non-fungible collection supply
// overflows due to the cost of minting individual tokens
++_supplies[collectionId];
++_balances[collectionId][to];
++_nftBalances[to];
}
}
function _transferFungible(
address from,
address to,
uint256 id,
uint256 value,
bool operatable
) internal {
require(operatable, "Inventory: non-approved sender");
require(value != 0, "Inventory: zero value");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
if (from != to) {
_balances[id][from] = balance - value;
// cannot overflow as supply cannot overflow
_balances[id][to] += value;
}
}
function _transferNFT(
address from,
address to,
uint256 id,
uint256 value,
bool operatable,
bool isBatch
) internal virtual {
require(value == 1, "Inventory: wrong NFT value");
uint256 owner = _owners[id];
require(from == address(owner), "Inventory: non-owned NFT");
if (!operatable) {
require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[id], "Inventory: non-approved sender");
}
_owners[id] = uint256(to);
if (!isBatch) {
_transferNFTUpdateBalances(from, to, 1);
_transferNFTUpdateCollection(from, to, id.getNonFungibleCollection(), 1);
}
}
function _transferNFTUpdateBalances(
address from,
address to,
uint256 amount
) internal virtual {
if (from != to) {
// cannot underflow as balance is verified through ownership
_nftBalances[from] -= amount;
// cannot overflow as supply cannot overflow
_nftBalances[to] += amount;
}
}
function _transferNFTUpdateCollection(
address from,
address to,
uint256 collectionId,
uint256 amount
) internal virtual {
if (from != to) {
// cannot underflow as balance is verified through ownership
_balances[collectionId][from] -= amount;
// cannot overflow as supply cannot overflow
_balances[collectionId][to] += amount;
}
}
///////////////////////////////////// Receiver Calls Internal /////////////////////////////////////
/**
* Queries whether a contract implements ERC1155TokenReceiver.
* @param _contract address of the contract.
* @return wheter the given contract implements ERC1155TokenReceiver.
*/
function _isERC1155TokenReceiver(address _contract) internal view returns (bool) {
bool success;
bool result;
bytes memory staticCallData = abi.encodeWithSelector(_ERC165_INTERFACE_ID, _ERC1155_TOKEN_RECEIVER_INTERFACE_ID);
assembly {
let call_ptr := add(0x20, staticCallData)
let call_size := mload(staticCallData)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(10000, _contract, call_ptr, call_size, output, 0x20) // 32 bytes
result := mload(output)
}
// (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas
assert(gasleft() > 158);
return success && result;
}
/**
* Calls {IERC721Receiver-onERC721Received} on a target contract.
* @dev Reverts if `to` is not a contract.
* @dev Reverts if the call to the target fails or is refused.
* @param from Previous token owner.
* @param to New token owner.
* @param nftId Identifier of the token transferred.
* @param data Optional data to send along with the receiver contract call.
*/
function _callOnERC721Received(
address from,
address to,
uint256 nftId,
bytes memory data
) internal {
require(IERC721Receiver(to).onERC721Received(_msgSender(), from, nftId, data) == _ERC721_RECEIVED, "Inventory: transfer refused");
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title IERC1155721InventoryBurnable interface.
* The function {IERC721Burnable-burnFrom(address,uint256)} is not provided as
* {IERC1155Burnable-burnFrom(address,uint256,uint256)} can be used instead.
*/
interface IERC1155721InventoryBurnable {
/**
* Burns some token (ERC1155-compatible).
* @dev Reverts if the sender is not approved.
* @dev Reverts if `id` does not represent a token.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and `value` is higher than `from`'s balance.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token which is not owned by `from`.
* @dev Emits an {IERC721-Transfer} event to the zero address if `id` represents a non-fungible token.
* @dev Emits an {IERC1155-TransferSingle} event to the zero address.
* @param from Address of the current token owner.
* @param id Identifier of the token to burn.
* @param value Amount of token to burn.
*/
function burnFrom(
address from,
uint256 id,
uint256 value
) external;
/**
* Burns multiple tokens (ERC1155-compatible).
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `ids` does not represent a token.
* @dev Reverts if one of `ids` represents a fungible token and `value` is 0.
* @dev Reverts if one of `ids` represents a fungible token and `value` is higher than `from`'s balance.
* @dev Reverts if one of `ids` represents a non-fungible token and `value` is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token which is not owned by `from`.
* @dev Emits an {IERC721-Transfer} event to the zero address for each burnt non-fungible token.
* @dev Emits an {IERC1155-TransferBatch} event to the zero address.
* @param from Address of the current tokens owner.
* @param ids Identifiers of the tokens to burn.
* @param values Amounts of tokens to burn.
*/
function batchBurnFrom(
address from,
uint256[] calldata ids,
uint256[] calldata values
) external;
/**
* Burns a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `nftIds` does not represent a non-fungible token.
* @dev Reverts if one of `nftIds` is not owned by `from`.
* @dev Emits an {IERC721-Transfer} event to the zero address for each of `nftIds`.
* @dev Emits an {IERC1155-TransferBatch} event to the zero address.
* @param from Current token owner.
* @param nftIds Identifiers of the tokens to transfer.
*/
function batchBurnFrom(address from, uint256[] calldata nftIds) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC1155721InventoryBurnable, a burnable ERC1155721Inventory.
*/
abstract contract ERC1155721InventoryBurnable is IERC1155721InventoryBurnable, ERC1155721Inventory {
//============================== ERC1155721InventoryBurnable =======================================/
/**
* Burns some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryBurnable-burnFrom(address,uint256,uint256)}.
*/
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
if (id.isFungibleToken()) {
_burnFungible(from, id, value, operatable);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, value, operatable, false);
emit Transfer(from, address(0), id);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, address(0), id, value);
}
/**
* Burns a batch of token (ERC1155-compatible).
* @dev See {IERC1155721InventoryBurnable-batchBurnFrom(address,uint256[],uint256[])}.
*/
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 nfCollectionId;
uint256 nfCollectionCount;
uint256 nftsCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, values[i], operatable);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, values[i], operatable, true);
emit Transfer(from, address(0), id);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nftsCount += nfCollectionCount;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
nftsCount += nfCollectionCount;
// cannot underflow as balance is verified through ownership
_nftBalances[from] -= nftsCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
/**
* Burns a batch of token (ERC721-compatible).
* @dev See {IERC1155721InventoryBurnable-batchBurnFrom(address,uint256[])}.
*/
function batchBurnFrom(address from, uint256[] memory nftIds) public virtual override {
address sender = _msgSender();
bool operatable = _isOperatable(from, sender);
uint256 length = nftIds.length;
uint256[] memory values = new uint256[](length);
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 nftId = nftIds[i];
values[i] = 1;
_burnNFT(from, nftId, values[i], operatable, true);
emit Transfer(from, address(0), nftId);
uint256 nextCollectionId = nftId.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
}
if (nfCollectionId != 0) {
_burnNFTUpdateCollection(from, nfCollectionId, nfCollectionCount);
_nftBalances[from] -= length;
}
emit TransferBatch(sender, from, address(0), nftIds, values);
}
//============================== Internal Helper Functions =======================================/
function _burnFungible(
address from,
uint256 id,
uint256 value,
bool operatable
) internal {
require(value != 0, "Inventory: zero value");
require(operatable, "Inventory: non-approved sender");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
_balances[id][from] = balance - value;
// Cannot underflow
_supplies[id] -= value;
}
function _burnNFT(
address from,
uint256 id,
uint256 value,
bool operatable,
bool isBatch
) internal virtual {
require(value == 1, "Inventory: wrong NFT value");
uint256 owner = _owners[id];
require(from == address(owner), "Inventory: non-owned NFT");
if (!operatable) {
require((owner & _APPROVAL_BIT_TOKEN_OWNER_ != 0) && _msgSender() == _nftApprovals[id], "Inventory: non-approved sender");
}
_owners[id] = _BURNT_NFT_OWNER;
if (!isBatch) {
_burnNFTUpdateCollection(from, id.getNonFungibleCollection(), 1);
// cannot underflow as balance is verified through NFT ownership
--_nftBalances[from];
}
}
function _burnNFTUpdateCollection(
address from,
uint256 collectionId,
uint256 amount
) internal virtual {
// cannot underflow as balance is verified through NFT ownership
_balances[collectionId][from] -= amount;
_supplies[collectionId] -= amount;
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155721/[email protected]
pragma solidity 0.6.8;
/**
* @title IERC1155721InventoryMintable interface.
* The function {IERC721Mintable-safeMint(address,uint256,bytes)} is not provided as
* {IERC1155Mintable-safeMint(address,uint256,uint256,bytes)} can be used instead.
*/
interface IERC1155721InventoryMintable {
/**
* Safely mints some token (ERC1155-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `id` is not a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token which has already been minted.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and there is an overflow of supply.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155Received} fails or is refused.
* @dev Emits an {IERC721-Transfer} event from the zero address if `id` represents a non-fungible token.
* @dev Emits an {IERC1155-TransferSingle} event from the zero address.
* @param to Address of the new token owner.
* @param id Identifier of the token to mint.
* @param value Amount of token to mint.
* @param data Optional data to send along to a receiver contract.
*/
function safeMint(
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if one of `ids` is not a token.
* @dev Reverts if one of `ids` represents a non-fungible token and its paired value is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token which has already been minted.
* @dev Reverts if one of `ids` represents a fungible token and its paired value is 0.
* @dev Reverts if one of `ids` represents a fungible token and there is an overflow of supply.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits an {IERC721-Transfer} event from the zero address for each non-fungible token minted.
* @dev Emits an {IERC1155-TransferBatch} event from the zero address.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to mint.
* @param values Amounts of tokens to mint.
* @param data Optional data to send along to a receiver contract.
*/
function safeBatchMint(
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
/**
* Unsafely mints a Non-Fungible Token (ERC721-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `nftId` does not represent a non-fungible token.
* @dev Reverts if `nftId` has already been minted.
* @dev Emits an {IERC721-Transfer} event from the zero address.
* @dev Emits an {IERC1155-TransferSingle} event from the zero address.
* @dev If `to` is a contract and supports ERC1155TokenReceiver, calls {IERC1155TokenReceiver-onERC1155Received} with empty data.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to mint.
*/
function mint(address to, uint256 nftId) external;
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if one of `nftIds` does not represent a non-fungible token.
* @dev Reverts if one of `nftIds` has already been minted.
* @dev Emits an {IERC721-Transfer} event from the zero address for each of `nftIds`.
* @dev Emits an {IERC1155-TransferBatch} event from the zero address.
* @dev If `to` is a contract and supports ERC1155TokenReceiver, calls {IERC1155TokenReceiver-onERC1155BatchReceived} with empty data.
* @param to Address of the new token owner.
* @param nftIds Identifiers of the tokens to mint.
*/
function batchMint(address to, uint256[] calldata nftIds) external;
/**
* Safely mints a token (ERC721-compatible).
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `tokenId` has already ben minted.
* @dev Reverts if `to` is a contract which does not implement IERC721Receiver or IERC1155TokenReceiver.
* @dev Reverts if `to` is an IERC1155TokenReceiver or IERC721TokenReceiver contract which refuses the transfer.
* @dev Emits an {IERC721-Transfer} event from the zero address.
* @dev Emits an {IERC1155-TransferSingle} event from the zero address.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to mint.
* @param data Optional data to pass along to the receiver call.
*/
function safeMint(
address to,
uint256 nftId,
bytes calldata data
) external;
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/token/ERC1155/[email protected]
pragma solidity 0.6.8;
/**
* @title ERC-1155 Inventory, additional creator interface
* @dev See https://eips.ethereum.org/EIPS/eip-1155
*/
interface IERC1155InventoryCreator {
/**
* Returns the creator of a collection, or the zero address if the collection has not been created.
* @dev Reverts if `collectionId` does not represent a collection.
* @param collectionId Identifier of the collection.
* @return The creator of a collection, or the zero address if the collection has not been created.
*/
function creator(uint256 collectionId) external view returns (address);
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @animoca/ethereum-contracts-core_library/contracts/utils/types/[email protected]
pragma solidity 0.6.8;
library UInt256ToDecimalString {
function toDecimalString(uint256 value) internal pure returns (string memory) {
// Inspired by OpenZeppelin's String.toString() implementation - MIT licence
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/8b10cb38d8fedf34f2d89b0ed604f2dceb76d6a9/contracts/utils/Strings.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// File @animoca/ethereum-contracts-assets_inventory/contracts/metadata/[email protected]
pragma solidity 0.6.8;
contract BaseMetadataURI is Ownable {
using UInt256ToDecimalString for uint256;
event BaseMetadataURISet(string baseMetadataURI);
string public baseMetadataURI;
function setBaseMetadataURI(string calldata baseMetadataURI_) external onlyOwner {
baseMetadataURI = baseMetadataURI_;
emit BaseMetadataURISet(baseMetadataURI_);
}
function _uri(uint256 id) internal view virtual returns (string memory) {
return string(abi.encodePacked(baseMetadataURI, id.toDecimalString()));
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @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, 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 {
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 `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 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.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_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());
}
}
}
// File @animoca/ethereum-contracts-core_library/contracts/access/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts access control over token
* minting operations.
*
* This module is used through inheritance. It will make available the modifier
* `onlyMinter`, which can be applied to the minting functions of your contract.
* Those functions will only be accessible to accounts with the minter role
* once the modifer is put in place.
*/
contract MinterRole is AccessControl {
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
/**
* Modifier to make a function callable only by accounts with the minter role.
*/
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: not a Minter");
_;
}
/**
* Constructor.
*/
constructor() internal {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
emit MinterAdded(_msgSender());
}
/**
* Validates whether or not the given account has been granted the minter role.
* @param account The account to validate.
* @return True if the account has been granted the minter role, false otherwise.
*/
function isMinter(address account) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
/**
* Grants the minter role to a non-minter.
* @param account The account to grant the minter role to.
*/
function addMinter(address account) public onlyMinter {
require(!isMinter(account), "MinterRole: already Minter");
grantRole(DEFAULT_ADMIN_ROLE, account);
emit MinterAdded(account);
}
/**
* Renounces the granted minter role.
*/
function renounceMinter() public onlyMinter {
renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
emit MinterRemoved(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <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 () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File contracts/solc-0.6/token/ERC1155721/REVVInventory.sol
pragma solidity ^0.6.8;
contract REVVInventory is
Ownable,
Pausable,
ERC1155721InventoryBurnable,
IERC1155721InventoryMintable,
IERC1155InventoryCreator,
BaseMetadataURI,
MinterRole
{
// solhint-disable-next-line const-name-snakecase
string public constant override name = "REVV Inventory";
// solhint-disable-next-line const-name-snakecase
string public constant override symbol = "REVV-I";
//================================== ERC1155MetadataURI =======================================/
/// @dev See {IERC1155MetadataURI-uri(uint256)}.
function uri(uint256 id) public view virtual override returns (string memory) {
return _uri(id);
}
//================================== ERC1155InventoryCreator =======================================/
/// @dev See {IERC1155InventoryCreator-creator(uint256)}.
function creator(uint256 collectionId) external view override returns (address) {
return _creator(collectionId);
}
// ===================================================================================================
// Admin Public Functions
// ===================================================================================================
//================================== Pausable =======================================/
function pause() external virtual {
require(owner() == _msgSender(), "Inventory: not the owner");
_pause();
}
function unpause() external virtual {
require(owner() == _msgSender(), "Inventory: not the owner");
_unpause();
}
//================================== ERC1155Inventory =======================================/
/**
* Creates a collection.
* @dev Reverts if `collectionId` does not represent a collection.
* @dev Reverts if `collectionId` has already been created.
* @dev Emits a {IERC1155Inventory-CollectionCreated} event.
* @param collectionId Identifier of the collection.
*/
function createCollection(uint256 collectionId) external onlyOwner {
_createCollection(collectionId);
}
//================================== ERC1155721InventoryMintable =======================================/
/**
* Unsafely mints a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256)}.
*/
function mint(address to, uint256 nftId) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_mint(to, nftId, "", false);
}
/**
* Unsafely mints a batch of Non-Fungible Tokens (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-batchMint(address,uint256[])}.
*/
function batchMint(address to, uint256[] memory nftIds) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_batchMint(to, nftIds);
}
/**
* Safely mints a Non-Fungible Token (ERC721-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,bytes)}.
*/
function safeMint(
address to,
uint256 nftId,
bytes memory data
) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_mint(to, nftId, data, true);
}
/**
* Safely mints some token (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeMint(address,uint256,uint256,bytes)}.
*/
function safeMint(
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_safeMint(to, id, value, data);
}
/**
* Safely mints a batch of tokens (ERC1155-compatible).
* @dev See {IERC1155721InventoryMintable-safeBatchMint(address,uint256[],uint256[],bytes)}.
*/
function safeBatchMint(
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
require(isMinter(_msgSender()), "Inventory: not a minter");
_safeBatchMint(to, ids, values, data);
}
//================================== ERC721 =======================================/
function transferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
require(!paused(), "Inventory: paused");
super.transferFrom(from, to, nftId);
}
function batchTransferFrom(
address from,
address to,
uint256[] memory nftIds
) public virtual override {
require(!paused(), "Inventory: paused");
super.batchTransferFrom(from, to, nftIds);
}
function safeTransferFrom(
address from,
address to,
uint256 nftId
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeTransferFrom(from, to, nftId);
}
function safeTransferFrom(
address from,
address to,
uint256 nftId,
bytes memory data
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeTransferFrom(from, to, nftId, data);
}
function batchBurnFrom(address from, uint256[] memory nftIds) public virtual override {
require(!paused(), "Inventory: paused");
super.batchBurnFrom(from, nftIds);
}
//================================== ERC1155 =======================================/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeTransferFrom(from, to, id, value, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual override {
require(!paused(), "Inventory: paused");
super.safeBatchTransferFrom(from, to, ids, values, data);
}
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
require(!paused(), "Inventory: paused");
super.burnFrom(from, id, value);
}
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
require(!paused(), "Inventory: paused");
super.batchBurnFrom(from, ids, values);
}
} | See {IERC1155-balanceOfBatch(address[],uint256[])}. | function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view virtual override returns (uint256[] memory) {
require(owners.length == ids.length, "Inventory: inconsistent arrays");
uint256[] memory balances = new uint256[](owners.length);
for (uint256 i = 0; i != owners.length; ++i) {
balances[i] = balanceOf(owners[i], ids[i]);
}
return balances;
}
| 2,505,677 |
./full_match/1/0x3D4a70e5F355EAd0690213Ae9909f3Dc41236E3C/sources/@gearbox-protocol/integrations-v2/contracts/adapters/convex/ConvexV1_BaseRewardPool.sol | Internal implementation for withdrawal functions - Invokes a safe allowance fast check call to target, with passed calldata - Enables reward tokens if rewards were claimed callData Data that the target contract will be called with claim Whether to claim rewards while withdrawing Fast check parameters: Input token: Phantom token (representing staked balance in the pool) Output token: Convex LP Token Input token is not allowed, since the target does not need to transferFrom | function _withdraw(
bytes memory callData,
bool claim,
bool disableTokenIn
) internal returns (bool) {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
_safeExecuteFastCheck(
creditAccount,
stakedPhantomToken,
address(stakingToken),
callData,
false,
disableTokenIn
);
if (claim) {
_enableRewardTokens(creditAccount, true);
}
return true;
}
| 16,431,952 |
/**
*Submitted for verification at Etherscan.io on 2021-04-03
*/
// SPDX-License-Identifier: BUSL-1.1
// File: @uniswap/lib/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/interfaces/IDMMFactory.sol
pragma solidity 0.6.12;
interface IDMMFactory {
function createPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps
) external returns (address pool);
function setFeeConfiguration(address feeTo, uint16 governmentFeeBps) external;
function setFeeToSetter(address) external;
function getFeeConfiguration() external view returns (address feeTo, uint16 governmentFeeBps);
function feeToSetter() external view returns (address);
function allPools(uint256) external view returns (address pool);
function allPoolsLength() external view returns (uint256);
function getUnamplifiedPool(IERC20 token0, IERC20 token1) external view returns (address);
function getPools(IERC20 token0, IERC20 token1)
external
view
returns (address[] memory _tokenPools);
function isPool(
IERC20 token0,
IERC20 token1,
address pool
) external view returns (bool);
}
// File: contracts/interfaces/IWETH.sol
pragma solidity 0.6.12;
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// File: contracts/interfaces/IDMMExchangeRouter.sol
pragma solidity 0.6.12;
/// @dev an simple interface for integration dApp to swap
interface IDMMExchangeRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function getAmountsOut(
uint256 amountIn,
address[] calldata poolsPath,
IERC20[] calldata path
) external view returns (uint256[] memory amounts);
function getAmountsIn(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path
) external view returns (uint256[] memory amounts);
}
// File: contracts/interfaces/IDMMLiquidityRouter.sol
pragma solidity 0.6.12;
/// @dev an simple interface for integration dApp to contribute liquidity
interface IDMMLiquidityRouter {
function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPoolETH(
IERC20 token,
uint32 ampBps,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function addLiquidityETH(
IERC20 token,
address pool,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityWithPermit(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityETHWithPermit(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
}
// File: contracts/interfaces/IDMMRouter01.sol
pragma solidity 0.6.12;
/// @dev full interface for router
interface IDMMRouter01 is IDMMExchangeRouter, IDMMLiquidityRouter {
function factory() external pure returns (address);
function weth() external pure returns (IWETH);
}
// File: contracts/interfaces/IDMMRouter02.sol
pragma solidity 0.6.12;
interface IDMMRouter02 is IDMMRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external;
}
// File: contracts/interfaces/IERC20Permit.sol
pragma solidity 0.6.12;
interface IERC20Permit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/interfaces/IDMMPool.sol
pragma solidity 0.6.12;
interface IDMMPool {
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 sync() external;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getTradeInfo()
external
view
returns (
uint112 _vReserve0,
uint112 _vReserve1,
uint112 reserve0,
uint112 reserve1,
uint256 feeInPrecision
);
function token0() external view returns (IERC20);
function token1() external view returns (IERC20);
function ampBps() external view returns (uint32);
function factory() external view returns (IDMMFactory);
function kLast() external view returns (uint256);
}
// File: contracts/libraries/DMMLibrary.sol
pragma solidity 0.6.12;
library DMMLibrary {
using SafeMath for uint256;
uint256 public constant PRECISION = 1e18;
// returns sorted token addresses, used to handle return values from pools sorted in this order
function sortTokens(IERC20 tokenA, IERC20 tokenB)
internal
pure
returns (IERC20 token0, IERC20 token1)
{
require(tokenA != tokenB, "DMMLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(address(token0) != address(0), "DMMLibrary: ZERO_ADDRESS");
}
/// @dev fetch the reserves and fee for a pool, used for trading purposes
function getTradeInfo(
address pool,
IERC20 tokenA,
IERC20 tokenB
)
internal
view
returns (
uint256 reserveA,
uint256 reserveB,
uint256 vReserveA,
uint256 vReserveB,
uint256 feeInPrecision
)
{
(IERC20 token0, ) = sortTokens(tokenA, tokenB);
uint256 reserve0;
uint256 reserve1;
uint256 vReserve0;
uint256 vReserve1;
(reserve0, reserve1, vReserve0, vReserve1, feeInPrecision) = IDMMPool(pool).getTradeInfo();
(reserveA, reserveB, vReserveA, vReserveB) = tokenA == token0
? (reserve0, reserve1, vReserve0, vReserve1)
: (reserve1, reserve0, vReserve1, vReserve0);
}
/// @dev fetches the reserves for a pool, used for liquidity adding
function getReserves(
address pool,
IERC20 tokenA,
IERC20 tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(IERC20 token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1) = IDMMPool(pool).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pool reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "DMMLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pool reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "DMMLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(PRECISION.sub(feeInPrecision)).div(PRECISION);
uint256 numerator = amountInWithFee.mul(vReserveOut);
uint256 denominator = vReserveIn.add(amountInWithFee);
amountOut = numerator.div(denominator);
require(reserveOut > amountOut, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
}
// given an output amount of an asset and pool reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "DMMLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > amountOut, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
uint256 numerator = vReserveIn.mul(amountOut);
uint256 denominator = vReserveOut.sub(amountOut);
amountIn = numerator.div(denominator).add(1);
// amountIn = floor(amountIN *PRECISION / (PRECISION - feeInPrecision));
numerator = amountIn.mul(PRECISION);
denominator = PRECISION.sub(feeInPrecision);
amountIn = numerator.add(denominator - 1).div(denominator);
}
// performs chained getAmountOut calculations on any number of pools
function getAmountsOut(
uint256 amountIn,
address[] memory poolsPath,
IERC20[] memory path
) internal view returns (uint256[] memory amounts) {
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) = getTradeInfo(poolsPath[i], path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(
amounts[i],
reserveIn,
reserveOut,
vReserveIn,
vReserveOut,
feeInPrecision
);
}
}
// performs chained getAmountIn calculations on any number of pools
function getAmountsIn(
uint256 amountOut,
address[] memory poolsPath,
IERC20[] memory path
) internal view returns (uint256[] memory amounts) {
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) = getTradeInfo(poolsPath[i - 1], path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(
amounts[i],
reserveIn,
reserveOut,
vReserveIn,
vReserveOut,
feeInPrecision
);
}
}
}
// File: contracts/periphery/DMMRouter02.sol
pragma solidity 0.6.12;
contract DMMRouter02 is IDMMRouter02 {
using SafeERC20 for IERC20;
using SafeERC20 for IWETH;
using SafeMath for uint256;
uint256 internal constant BPS = 10000;
address public immutable override factory;
IWETH public immutable override weth;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "DMMRouter: EXPIRED");
_;
}
constructor(address _factory, IWETH _weth) public {
factory = _factory;
weth = _weth;
}
receive() external payable {
assert(msg.sender == address(weth)); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual view returns (uint256 amountA, uint256 amountB) {
(uint256 reserveA, uint256 reserveB) = DMMLibrary.getReserves(pool, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = DMMLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, "DMMRouter: INSUFFICIENT_B_AMOUNT");
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = DMMLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, "DMMRouter: INSUFFICIENT_A_AMOUNT");
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
verifyPoolAddress(tokenA, tokenB, pool);
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
pool,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
// using tokenA.safeTransferFrom will get "Stack too deep"
SafeERC20.safeTransferFrom(tokenA, msg.sender, pool, amountA);
SafeERC20.safeTransferFrom(tokenB, msg.sender, pool, amountB);
liquidity = IDMMPool(pool).mint(to);
}
function addLiquidityETH(
IERC20 token,
address pool,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
public
override
payable
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
verifyPoolAddress(token, weth, pool);
(amountToken, amountETH) = _addLiquidity(
token,
weth,
pool,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
token.safeTransferFrom(msg.sender, pool, amountToken);
weth.deposit{value: amountETH}();
weth.safeTransfer(pool, amountETH);
liquidity = IDMMPool(pool).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) {
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
}
function addLiquidityNewPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
override
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
address pool;
if (ampBps == BPS) {
pool = IDMMFactory(factory).getUnamplifiedPool(tokenA, tokenB);
}
if (pool == address(0)) {
pool = IDMMFactory(factory).createPool(tokenA, tokenB, ampBps);
}
(amountA, amountB, liquidity) = addLiquidity(
tokenA,
tokenB,
pool,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
}
function addLiquidityNewPoolETH(
IERC20 token,
uint32 ampBps,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
override
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
address pool;
if (ampBps == BPS) {
pool = IDMMFactory(factory).getUnamplifiedPool(token, weth);
}
if (pool == address(0)) {
pool = IDMMFactory(factory).createPool(token, weth, ampBps);
}
(amountToken, amountETH, liquidity) = addLiquidityETH(
token,
pool,
amountTokenDesired,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
verifyPoolAddress(tokenA, tokenB, pool);
IERC20(pool).safeTransferFrom(msg.sender, pool, liquidity); // send liquidity to pool
(uint256 amount0, uint256 amount1) = IDMMPool(pool).burn(to);
(IERC20 token0, ) = DMMLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, "DMMRouter: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "DMMRouter: INSUFFICIENT_B_AMOUNT");
}
function removeLiquidityETH(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256 amountToken, uint256 amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
weth,
pool,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
token.safeTransfer(to, amountToken);
IWETH(weth).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountA, uint256 amountB) {
uint256 value = approveMax ? uint256(-1) : liquidity;
IERC20Permit(pool).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(
tokenA,
tokenB,
pool,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
}
function removeLiquidityETHWithPermit(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external override returns (uint256 amountToken, uint256 amountETH) {
uint256 value = approveMax ? uint256(-1) : liquidity;
IERC20Permit(pool).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(
token,
pool,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256 amountETH) {
(, amountETH) = removeLiquidity(
token,
weth,
pool,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
token.safeTransfer(to, IERC20(token).balanceOf(address(this)));
IWETH(weth).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external override returns (uint256 amountETH) {
uint256 value = approveMax ? uint256(-1) : liquidity;
IERC20Permit(pool).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token,
pool,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pool
function _swap(
uint256[] memory amounts,
address[] memory poolsPath,
IERC20[] memory path,
address _to
) private {
for (uint256 i; i < path.length - 1; i++) {
(IERC20 input, IERC20 output) = (path[i], path[i + 1]);
(IERC20 token0, ) = DMMLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? poolsPath[i + 1] : _to;
IDMMPool(poolsPath[i]).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory poolsPath,
IERC20[] memory path,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsOut(amountIn, poolsPath, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
IERC20(path[0]).safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] memory poolsPath,
IERC20[] memory path,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
require(amounts[0] <= amountInMax, "DMMRouter: EXCESSIVE_INPUT_AMOUNT");
path[0].safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
}
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override payable ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsOut(msg.value, poolsPath, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
IWETH(weth).deposit{value: amounts[0]}();
weth.safeTransfer(poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
}
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
require(amounts[0] <= amountInMax, "DMMRouter: EXCESSIVE_INPUT_AMOUNT");
path[0].safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, address(this));
IWETH(weth).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsOut(amountIn, poolsPath, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
path[0].safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, address(this));
IWETH(weth).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override payable ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
require(amounts[0] <= msg.value, "DMMRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(weth).deposit{value: amounts[0]}();
weth.safeTransfer(poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) {
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pool
function _swapSupportingFeeOnTransferTokens(
address[] memory poolsPath,
IERC20[] memory path,
address _to
) internal {
verifyPoolsPathSwap(poolsPath, path);
for (uint256 i; i < path.length - 1; i++) {
(IERC20 input, IERC20 output) = (path[i], path[i + 1]);
(IERC20 token0, ) = DMMLibrary.sortTokens(input, output);
IDMMPool pool = IDMMPool(poolsPath[i]);
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) = DMMLibrary.getTradeInfo(poolsPath[i], input, output);
uint256 amountInput = IERC20(input).balanceOf(address(pool)).sub(reserveIn);
amountOutput = DMMLibrary.getAmountOut(
amountInput,
reserveIn,
reserveOut,
vReserveIn,
vReserveOut,
feeInPrecision
);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2 ? poolsPath[i + 1] : _to;
pool.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory poolsPath,
IERC20[] memory path,
address to,
uint256 deadline
) public override ensure(deadline) {
path[0].safeTransferFrom(msg.sender, poolsPath[0], amountIn);
uint256 balanceBefore = path[path.length - 1].balanceOf(to);
_swapSupportingFeeOnTransferTokens(poolsPath, path, to);
uint256 balanceAfter = path[path.length - 1].balanceOf(to);
require(
balanceAfter >= balanceBefore.add(amountOutMin),
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override payable ensure(deadline) {
require(path[0] == weth, "DMMRouter: INVALID_PATH");
uint256 amountIn = msg.value;
IWETH(weth).deposit{value: amountIn}();
weth.safeTransfer(poolsPath[0], amountIn);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(poolsPath, path, to);
require(
path[path.length - 1].balanceOf(to).sub(balanceBefore) >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override ensure(deadline) {
require(path[path.length - 1] == weth, "DMMRouter: INVALID_PATH");
path[0].safeTransferFrom(msg.sender, poolsPath[0], amountIn);
_swapSupportingFeeOnTransferTokens(poolsPath, path, address(this));
uint256 amountOut = IWETH(weth).balanceOf(address(this));
require(amountOut >= amountOutMin, "DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(weth).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
/// @dev get the amount of tokenB for adding liquidity with given amount of token A and the amount of tokens in the pool
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external override pure returns (uint256 amountB) {
return DMMLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountsOut(
uint256 amountIn,
address[] calldata poolsPath,
IERC20[] calldata path
) external override view returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
return DMMLibrary.getAmountsOut(amountIn, poolsPath, path);
}
function getAmountsIn(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path
) external override view returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
return DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
}
function verifyPoolsPathSwap(address[] memory poolsPath, IERC20[] memory path) internal view {
require(path.length >= 2, "DMMRouter: INVALID_PATH");
require(poolsPath.length == path.length - 1, "DMMRouter: INVALID_POOLS_PATH");
for (uint256 i = 0; i < poolsPath.length; i++) {
verifyPoolAddress(path[i], path[i + 1], poolsPath[i]);
}
}
function verifyPoolAddress(
IERC20 tokenA,
IERC20 tokenB,
address pool
) internal view {
require(IDMMFactory(factory).isPool(tokenA, tokenB, pool), "DMMRouter: INVALID_POOL");
}
} | SWAP requires the initial amount to have already been sent to the first pool | function _swap(
uint256[] memory amounts,
address[] memory poolsPath,
IERC20[] memory path,
address _to
) private {
for (uint256 i; i < path.length - 1; i++) {
(IERC20 input, IERC20 output) = (path[i], path[i + 1]);
(IERC20 token0, ) = DMMLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? poolsPath[i + 1] : _to;
IDMMPool(poolsPath[i]).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
| 2,097,399 |
contract Multiplicator
{
//Gotta be generous sometimes
address public Owner = msg.sender;
mapping (address => bool) winner; //keeping track of addresses that have already benefited
function multiplicate(address adr) public payable
{
if(msg.value>=this.balance)
{
require(winner[msg.sender] == false);// every address can only benefit once, don't be greedy
winner[msg.sender] = true;
adr.transfer(this.balance+msg.value);
}
}
function kill() {
require(msg.sender==Owner);
selfdestruct(msg.sender);
}
//If you want to be generous you can just send ether to this contract without calling any function and others will profit by calling multiplicate
function () payable {}
} | If you want to be generous you can just send ether to this contract without calling any function and others will profit by calling multiplicate | function () payable {}
| 1,029,036 |
pragma solidity ^0.6.6;
import "./ERC20.sol";
import "./Address.sol";
import "./BokkyPooBahsDateTimeLibrary.sol";
import "./Strings.sol";
/**
* @title ACOToken
* @dev The implementation of the ACO token.
* The token is ERC20 compliance.
*/
contract ACOToken is ERC20 {
using Address for address;
/**
* @dev Struct to store the accounts that generated tokens with a collateral deposit.
*/
struct TokenCollateralized {
/**
* @dev Current amount of tokens.
*/
uint256 amount;
/**
* @dev Index on the collateral owners array.
*/
uint256 index;
}
/**
* @dev Emitted when collateral is deposited on the contract.
* @param account Address of the collateral owner.
* @param amount Amount of collateral deposited.
*/
event CollateralDeposit(address indexed account, uint256 amount);
/**
* @dev Emitted when collateral is withdrawn from the contract.
* @param account Address of the collateral destination.
* @param amount Amount of collateral withdrawn.
* @param fee The fee amount charged on the withdrawal.
*/
event CollateralWithdraw(address indexed account, uint256 amount, uint256 fee);
/**
* @dev Emitted when the collateral is used on an assignment.
* @param from Address of the account of the collateral owner.
* @param to Address of the account that exercises tokens to get the collateral.
* @param paidAmount Amount paid to the collateral owner.
* @param tokenAmount Amount of tokens used to exercise.
*/
event Assigned(address indexed from, address indexed to, uint256 paidAmount, uint256 tokenAmount);
/**
* @dev The ERC20 token address for the underlying asset (0x0 for Ethereum).
*/
address public underlying;
/**
* @dev The ERC20 token address for the strike asset (0x0 for Ethereum).
*/
address public strikeAsset;
/**
* @dev Address of the fee destination charged on the exercise.
*/
address payable public feeDestination;
/**
* @dev True if the type is CALL, false for PUT.
*/
bool public isCall;
/**
* @dev The strike price for the token with the strike asset precision.
*/
uint256 public strikePrice;
/**
* @dev The UNIX time for the token expiration.
*/
uint256 public expiryTime;
/**
* @dev The total amount of collateral on the contract.
*/
uint256 public totalCollateral;
/**
* @dev The fee value. It is a percentage value (100000 is 100%).
*/
uint256 public acoFee;
/**
* @dev Symbol of the underlying asset.
*/
string public underlyingSymbol;
/**
* @dev Symbol of the strike asset.
*/
string public strikeAssetSymbol;
/**
* @dev Decimals for the underlying asset.
*/
uint8 public underlyingDecimals;
/**
* @dev Decimals for the strike asset.
*/
uint8 public strikeAssetDecimals;
/**
* @dev Underlying precision. (10 ^ underlyingDecimals)
*/
uint256 internal underlyingPrecision;
/**
* @dev Accounts that generated tokens with a collateral deposit.
*/
mapping(address => TokenCollateralized) internal tokenData;
/**
* @dev Array with all accounts with collateral deposited.
*/
address[] internal _collateralOwners;
/**
* @dev Internal data to control the reentrancy.
*/
bool internal _notEntered;
/**
* @dev Modifier to check if the token is not expired.
* It is executed only while the token is not expired.
*/
modifier notExpired() {
require(_notExpired(), "ACOToken::Expired");
_;
}
/**
* @dev Modifier to prevents a contract from calling itself during the function execution.
*/
modifier nonReentrant() {
require(_notEntered, "ACOToken::Reentry");
_notEntered = false;
_;
_notEntered = true;
}
/**
* @dev Function to initialize the contract.
* It should be called when creating the token.
* It must be called only once. The `assert` is to guarantee that behavior.
* @param _underlying Address of the underlying asset (0x0 for Ethereum).
* @param _strikeAsset Address of the strike asset (0x0 for Ethereum).
* @param _isCall True if the type is CALL, false for PUT.
* @param _strikePrice The strike price with the strike asset precision.
* @param _expiryTime The UNIX time for the token expiration.
* @param _acoFee Value of the ACO fee. It is a percentage value (100000 is 100%).
* @param _feeDestination Address of the fee destination charged on the exercise.
*/
function init(
address _underlying,
address _strikeAsset,
bool _isCall,
uint256 _strikePrice,
uint256 _expiryTime,
uint256 _acoFee,
address payable _feeDestination
) public {
require(underlying == address(0) && strikeAsset == address(0) && strikePrice == 0, "ACOToken::init: Already initialized");
require(_expiryTime > now, "ACOToken::init: Invalid expiry");
require(_strikePrice > 0, "ACOToken::init: Invalid strike price");
require(_underlying != _strikeAsset, "ACOToken::init: Same assets");
require(_acoFee <= 500, "ACOToken::init: Invalid ACO fee"); // Maximum is 0.5%
require(_isEther(_underlying) || _underlying.isContract(), "ACOToken::init: Invalid underlying");
require(_isEther(_strikeAsset) || _strikeAsset.isContract(), "ACOToken::init: Invalid strike asset");
underlying = _underlying;
strikeAsset = _strikeAsset;
isCall = _isCall;
strikePrice = _strikePrice;
expiryTime = _expiryTime;
acoFee = _acoFee;
feeDestination = _feeDestination;
underlyingDecimals = _getAssetDecimals(_underlying);
strikeAssetDecimals = _getAssetDecimals(_strikeAsset);
underlyingSymbol = _getAssetSymbol(_underlying);
strikeAssetSymbol = _getAssetSymbol(_strikeAsset);
underlyingPrecision = 10 ** uint256(underlyingDecimals);
_notEntered = true;
}
/**
* @dev Function to guarantee that the contract will not receive ether directly.
*/
receive() external payable {
revert();
}
/**
* @dev Function to get the token name.
*/
function name() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token symbol, that it is equal to the name.
*/
function symbol() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token decimals, that it is equal to the underlying asset decimals.
*/
function decimals() public view override returns(uint8) {
return underlyingDecimals;
}
/**
* @dev Function to get the current amount of collateral for an account.
* @param account Address of the account.
* @return The current amount of collateral.
*/
function currentCollateral(address account) public view returns(uint256) {
return getCollateralAmount(currentCollateralizedTokens(account));
}
/**
* @dev Function to get the current amount of unassignable collateral for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the unassignable collateral is equal to the account's collateral balance.
* @param account Address of the account.
* @return The respective amount of unassignable collateral.
*/
function unassignableCollateral(address account) public view returns(uint256) {
return getCollateralAmount(unassignableTokens(account));
}
/**
* @dev Function to get the current amount of assignable collateral for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the assignable collateral is zero.
* @param account Address of the account.
* @return The respective amount of assignable collateral.
*/
function assignableCollateral(address account) public view returns(uint256) {
return getCollateralAmount(assignableTokens(account));
}
/**
* @dev Function to get the current amount of collateralized tokens for an account.
* @param account Address of the account.
* @return The current amount of collateralized tokens.
*/
function currentCollateralizedTokens(address account) public view returns(uint256) {
return tokenData[account].amount;
}
/**
* @dev Function to get the current amount of unassignable tokens for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the unassignable tokens is equal to the account's collateralized tokens.
* @param account Address of the account.
* @return The respective amount of unassignable tokens.
*/
function unassignableTokens(address account) public view returns(uint256) {
if (balanceOf(account) > tokenData[account].amount) {
return tokenData[account].amount;
} else {
return balanceOf(account);
}
}
/**
* @dev Function to get the current amount of assignable tokens for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the assignable tokens is zero.
* @param account Address of the account.
* @return The respective amount of assignable tokens.
*/
function assignableTokens(address account) public view returns(uint256) {
return _getAssignableAmount(account);
}
/**
* @dev Function to get the equivalent collateral amount for a token amount.
* @param tokenAmount Amount of tokens.
* @return The respective amount of collateral.
*/
function getCollateralAmount(uint256 tokenAmount) public view returns(uint256) {
if (isCall) {
return tokenAmount;
} else if (tokenAmount > 0) {
return _getTokenStrikePriceRelation(tokenAmount);
} else {
return 0;
}
}
/**
* @dev Function to get the equivalent token amount for a collateral amount.
* @param collateralAmount Amount of collateral.
* @return The respective amount of tokens.
*/
function getTokenAmount(uint256 collateralAmount) public view returns(uint256) {
if (isCall) {
return collateralAmount;
} else if (collateralAmount > 0) {
return collateralAmount.mul(underlyingPrecision).div(strikePrice);
} else {
return 0;
}
}
/**
* @dev Function to get the data for exercise of an amount of token.
* @param tokenAmount Amount of tokens.
* @return The asset and the respective amount that should be sent to get the collateral.
*/
function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) {
if (isCall) {
return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount));
} else {
return (underlying, tokenAmount);
}
}
/**
* @dev Function to get the collateral asset.
* @return The address of the collateral asset.
*/
function collateral() public view returns(address) {
if (isCall) {
return underlying;
} else {
return strikeAsset;
}
}
/**
* @dev Function to mint tokens with Ether deposited as collateral.
* NOTE: The function only works when the token is NOT expired yet.
*/
function mintPayable() external payable {
require(_isEther(collateral()), "ACOToken::mintPayable: Invalid call");
_mintToken(msg.sender, msg.value);
}
/**
* @dev Function to mint tokens with Ether deposited as collateral to an informed account.
* However, the minted tokens are assigned to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account that will be the collateral owner.
*/
function mintToPayable(address account) external payable {
require(_isEther(collateral()), "ACOToken::mintToPayable: Invalid call");
_mintToken(account, msg.value);
}
/**
* @dev Function to mint tokens with ERC20 deposited as collateral.
* NOTE: The function only works when the token is NOT expired yet.
* @param collateralAmount Amount of collateral deposited.
*/
function mint(uint256 collateralAmount) external {
address _collateral = collateral();
require(!_isEther(_collateral), "ACOToken::mint: Invalid call");
require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mint: Invalid transfer");
_mintToken(msg.sender, collateralAmount);
}
/**
* @dev Function to mint tokens with ERC20 deposited as collateral to an informed account.
* However, the minted tokens are assigned to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account that will be the collateral owner.
* @param collateralAmount Amount of collateral deposited.
*/
function mintTo(address account, uint256 collateralAmount) external {
address _collateral = collateral();
require(!_isEther(_collateral), "ACOToken::mintTo: Invalid call");
require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mintTo: Invalid transfer");
_mintToken(account, collateralAmount);
}
/**
* @dev Function to burn tokens and get the collateral, not assigned, back.
* NOTE: The function only works when the token is NOT expired yet.
* @param tokenAmount Amount of tokens to be burned.
*/
function burn(uint256 tokenAmount) external {
_burn(msg.sender, tokenAmount);
}
/**
* @dev Function to burn tokens from a specific account and send the collateral to its address.
* The token allowance must be respected.
* The collateral is returned to the account address, not to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function burnFrom(address account, uint256 tokenAmount) external {
_burn(account, tokenAmount);
}
/**
* @dev Function to get the collateral, not assigned, back.
* NOTE: The function only works when the token IS expired.
*/
function redeem() external {
_redeem(msg.sender);
}
/**
* @dev Function to get the collateral from a specific account sent back to its address .
* The token allowance must be respected.
* The collateral is returned to the account address, not to the transaction sender.
* NOTE: The function only works when the token IS expired.
* @param account Address of the account.
*/
function redeemFrom(address account) external {
_redeem(account);
}
/**
* @dev Function to exercise the tokens, paying to get the equivalent collateral.
* The paid amount is sent to the collateral owners that were assigned.
* NOTE: The function only works when the token is NOT expired.
* @param tokenAmount Amount of tokens.
*/
function exercise(uint256 tokenAmount) external payable {
_exercise(msg.sender, tokenAmount);
}
/**
* @dev Function to exercise the tokens from an account, paying to get the equivalent collateral.
* The token allowance must be respected.
* The paid amount is sent to the collateral owners that were assigned.
* The collateral is transferred to the account address, not to the transaction sender.
* NOTE: The function only works when the token is NOT expired.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
*/
function exerciseFrom(address account, uint256 tokenAmount) external payable {
_exercise(account, tokenAmount);
}
/**
* @dev Function to exercise the tokens, paying to get the equivalent collateral.
* The paid amount is sent to the collateral owners (on accounts list) that were assigned.
* NOTE: The function only works when the token is NOT expired.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get collateral from.
*/
function exerciseAccounts(uint256 tokenAmount, address[] calldata accounts) external payable {
_exerciseFromAccounts(msg.sender, tokenAmount, accounts);
}
/**
* @dev Function to exercise the tokens from a specific account, paying to get the equivalent collateral sent to its address.
* The token allowance must be respected.
* The paid amount is sent to the collateral owners (on accounts list) that were assigned.
* The collateral is transferred to the account address, not to the transaction sender.
* NOTE: The function only works when the token is NOT expired.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the deposited collateral.
*/
function exerciseAccountsFrom(address account, uint256 tokenAmount, address[] calldata accounts) external payable {
_exerciseFromAccounts(account, tokenAmount, accounts);
}
/**
* @dev Function to burn the tokens after expiration.
* It is an optional function to `clear` the account wallet from an expired and not functional token.
* NOTE: The function only works when the token IS expired.
*/
function clear() external {
_clear(msg.sender);
}
/**
* @dev Function to burn the tokens from an account after expiration.
* It is an optional function to `clear` the account wallet from an expired and not functional token.
* The token allowance must be respected.
* NOTE: The function only works when the token IS expired.
* @param account Address of the account.
*/
function clearFrom(address account) external {
_clear(account);
}
/**
* @dev Internal function to burn the tokens from an account after expiration.
* @param account Address of the account.
*/
function _clear(address account) internal {
require(!_notExpired(), "ACOToken::_clear: Token not expired yet");
require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method");
_callBurn(account, balanceOf(account));
}
/**
* @dev Internal function to redeem respective collateral from an account.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
*/
function _redeemCollateral(address account, uint256 tokenAmount) internal {
require(_accountHasCollateral(account), "ACOToken::_redeemCollateral: No collateral available");
require(tokenAmount > 0, "ACOToken::_redeemCollateral: Invalid token amount");
TokenCollateralized storage data = tokenData[account];
data.amount = data.amount.sub(tokenAmount);
_removeCollateralDataIfNecessary(account);
_transferCollateral(account, getCollateralAmount(tokenAmount), false);
}
/**
* @dev Internal function to mint tokens.
* The tokens are minted for the transaction sender.
* @param account Address of the account.
* @param collateralAmount Amount of collateral deposited.
*/
function _mintToken(address account, uint256 collateralAmount) nonReentrant notExpired internal {
require(collateralAmount > 0, "ACOToken::_mintToken: Invalid collateral amount");
if (!_accountHasCollateral(account)) {
tokenData[account].index = _collateralOwners.length;
_collateralOwners.push(account);
}
uint256 tokenAmount = getTokenAmount(collateralAmount);
tokenData[account].amount = tokenData[account].amount.add(tokenAmount);
totalCollateral = totalCollateral.add(collateralAmount);
emit CollateralDeposit(account, collateralAmount);
super._mintAction(msg.sender, tokenAmount);
}
/**
* @dev Internal function to transfer tokens.
* The token transfer only works when the token is NOT expired.
* @param sender Source of the tokens.
* @param recipient Destination address for the tokens.
* @param amount Amount of tokens.
*/
function _transfer(address sender, address recipient, uint256 amount) notExpired internal override {
super._transferAction(sender, recipient, amount);
}
/**
* @dev Internal function to set the token permission from an account to another address.
* The token approval only works when the token is NOT expired.
* @param owner Address of the token owner.
* @param spender Address of the spender authorized.
* @param amount Amount of tokens authorized.
*/
function _approve(address owner, address spender, uint256 amount) notExpired internal override {
super._approveAction(owner, spender, amount);
}
/**
* @dev Internal function to transfer collateral.
* When there is a fee, the calculated fee is also transferred to the destination fee address.
* @param recipient Destination address for the collateral.
* @param collateralAmount Amount of collateral.
* @param hasFee Whether a fee should be applied to the collateral amount.
*/
function _transferCollateral(address recipient, uint256 collateralAmount, bool hasFee) internal {
require(recipient != address(0), "ACOToken::_transferCollateral: Invalid recipient");
totalCollateral = totalCollateral.sub(collateralAmount);
uint256 fee = 0;
if (hasFee) {
fee = collateralAmount.mul(acoFee).div(100000);
collateralAmount = collateralAmount.sub(fee);
}
address _collateral = collateral();
if (_isEther(_collateral)) {
payable(recipient).transfer(collateralAmount);
if (fee > 0) {
feeDestination.transfer(fee);
}
} else {
require(IERC20(_collateral).transfer(recipient, collateralAmount), "ACOToken::_transferCollateral: Invalid transfer");
if (fee > 0) {
require(IERC20(_collateral).transfer(feeDestination, fee), "ACOToken::_transferCollateral: Invalid transfer fee");
}
}
emit CollateralWithdraw(recipient, collateralAmount, fee);
}
/**
* @dev Internal function to exercise the tokens from an account.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _exercise(address account, uint256 tokenAmount) nonReentrant internal {
_validateAndBurn(account, tokenAmount);
_exerciseOwners(account, tokenAmount);
_transferCollateral(account, getCollateralAmount(tokenAmount), true);
}
/**
* @dev Internal function to exercise the tokens from an account.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the collateral from.
*/
function _exerciseFromAccounts(address account, uint256 tokenAmount, address[] memory accounts) nonReentrant internal {
_validateAndBurn(account, tokenAmount);
_exerciseAccounts(account, tokenAmount, accounts);
_transferCollateral(account, getCollateralAmount(tokenAmount), true);
}
/**
* @dev Internal function to exercise the assignable tokens from the stored list of collateral owners.
* @param exerciseAccount Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _exerciseOwners(address exerciseAccount, uint256 tokenAmount) internal {
uint256 start = _collateralOwners.length - 1;
for (uint256 i = start; i >= 0; --i) {
if (tokenAmount == 0) {
break;
}
tokenAmount = _exerciseAccount(_collateralOwners[i], tokenAmount, exerciseAccount);
}
require(tokenAmount == 0, "ACOToken::_exerciseOwners: Invalid remaining amount");
}
/**
* @dev Internal function to exercise the assignable tokens from an accounts list.
* @param exerciseAccount Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the collateral from.
*/
function _exerciseAccounts(address exerciseAccount, uint256 tokenAmount, address[] memory accounts) internal {
for (uint256 i = 0; i < accounts.length; ++i) {
if (tokenAmount == 0) {
break;
}
tokenAmount = _exerciseAccount(accounts[i], tokenAmount, exerciseAccount);
}
require(tokenAmount == 0, "ACOToken::_exerciseAccounts: Invalid remaining amount");
}
/**
* @dev Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
* @param exerciseAccount Address of the account that is exercising.
* @return Remaining amount of tokens.
*/
function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) {
uint256 available = _getAssignableAmount(account);
if (available > 0) {
TokenCollateralized storage data = tokenData[account];
uint256 valueToTransfer;
if (available < tokenAmount) {
valueToTransfer = available;
tokenAmount = tokenAmount.sub(available);
} else {
valueToTransfer = tokenAmount;
tokenAmount = 0;
}
(address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer);
data.amount = data.amount.sub(valueToTransfer);
_removeCollateralDataIfNecessary(account);
if (_isEther(exerciseAsset)) {
payable(account).transfer(amount);
} else {
require(IERC20(exerciseAsset).transfer(account, amount), "ACOToken::_exerciseAccount: Invalid transfer");
}
emit Assigned(account, exerciseAccount, amount, valueToTransfer);
}
return tokenAmount;
}
/**
* @dev Internal function to validate the exercise operation and burn the respective tokens.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal {
require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount");
// Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens.
if (_accountHasCollateral(account)) {
require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised");
require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available");
}
_callBurn(account, tokenAmount);
(address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount);
if (_isEther(exerciseAsset)) {
require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount");
} else {
require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected");
require(IERC20(exerciseAsset).transferFrom(msg.sender, address(this), expectedAmount), "ACOToken::_validateAndBurn: Fail to receive asset");
}
}
/**
* @dev Internal function to calculate the token strike price relation.
* @param tokenAmount Amount of tokens.
* @return Calculated value with strike asset precision.
*/
function _getTokenStrikePriceRelation(uint256 tokenAmount) internal view returns(uint256) {
return tokenAmount.mul(strikePrice).div(underlyingPrecision);
}
/**
* @dev Internal function to get the collateral sent back from an account.
* Function to be called when the token IS expired.
* @param account Address of the account.
*/
function _redeem(address account) nonReentrant internal {
require(!_notExpired(), "ACOToken::_redeem: Token not expired yet");
_redeemCollateral(account, tokenData[account].amount);
super._burnAction(account, balanceOf(account));
}
/**
* @dev Internal function to burn tokens from an account and get the collateral, not assigned, back.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function _burn(address account, uint256 tokenAmount) nonReentrant notExpired internal {
_redeemCollateral(account, tokenAmount);
_callBurn(account, tokenAmount);
}
/**
* @dev Internal function to burn tokens.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function _callBurn(address account, uint256 tokenAmount) internal {
if (account == msg.sender) {
super._burnAction(account, tokenAmount);
} else {
super._burnFrom(account, tokenAmount);
}
}
/**
* @dev Internal function to get the amount of assignable token from an account.
* @param account Address of the account.
* @return The assignable amount of tokens.
*/
function _getAssignableAmount(address account) internal view returns(uint256) {
if (tokenData[account].amount > balanceOf(account)) {
return tokenData[account].amount.sub(balanceOf(account));
} else {
return 0;
}
}
/**
* @dev Internal function to remove the token data with collateral if its total amount was assigned.
* @param account Address of account.
*/
function _removeCollateralDataIfNecessary(address account) internal {
TokenCollateralized storage data = tokenData[account];
if (!_hasCollateral(data)) {
uint256 lastIndex = _collateralOwners.length - 1;
if (lastIndex != data.index) {
address last = _collateralOwners[lastIndex];
tokenData[last].index = data.index;
_collateralOwners[data.index] = last;
}
_collateralOwners.pop();
delete tokenData[account];
}
}
/**
* @dev Internal function to get if the token is not expired.
* @return Whether the token is NOT expired.
*/
function _notExpired() internal view returns(bool) {
return now <= expiryTime;
}
/**
* @dev Internal function to get if an account has collateral deposited.
* @param account Address of the account.
* @return Whether the account has collateral deposited.
*/
function _accountHasCollateral(address account) internal view returns(bool) {
return _hasCollateral(tokenData[account]);
}
/**
* @dev Internal function to get if an account has collateral deposited.
* @param data Token data from an account.
* @return Whether the account has collateral deposited.
*/
function _hasCollateral(TokenCollateralized storage data) internal view returns(bool) {
return data.amount > 0;
}
/**
* @dev Internal function to get if the address is for Ethereum (0x0).
* @param _address Address to be checked.
* @return Whether the address is for Ethereum.
*/
function _isEther(address _address) internal pure returns(bool) {
return _address == address(0);
}
/**
* @dev Internal function to get the token name.
* The token name is assembled with the token data:
* ACO UNDERLYING_SYMBOL-EXPIRYTIME-STRIKE_PRICE_STRIKE_ASSET_SYMBOL-TYPE
* @return The token name.
*/
function _name() internal view returns(string memory) {
return string(abi.encodePacked(
"ACO ",
underlyingSymbol,
"-",
_getFormattedStrikePrice(),
strikeAssetSymbol,
"-",
_getType(),
"-",
_getFormattedExpiryTime()
));
}
/**
* @dev Internal function to get the token type description.
* @return The token type description.
*/
function _getType() internal view returns(string memory) {
if (isCall) {
return "C";
} else {
return "P";
}
}
/**
* @dev Internal function to get the expiry time formatted.
* @return The expiry time formatted.
*/
function _getFormattedExpiryTime() internal view returns(string memory) {
(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(expiryTime);
return string(abi.encodePacked(
_getNumberWithTwoCaracters(day),
_getMonthFormatted(month),
_getYearFormatted(year),
"-",
_getNumberWithTwoCaracters(hour),
_getNumberWithTwoCaracters(minute),
"UTC"
));
}
/**
* @dev Internal function to get the year formatted with 2 characters.
* @return The year formatted.
*/
function _getYearFormatted(uint256 year) internal pure returns(string memory) {
bytes memory yearBytes = bytes(Strings.toString(year));
bytes memory result = new bytes(2);
uint256 startIndex = yearBytes.length - 2;
for (uint256 i = startIndex; i < yearBytes.length; i++) {
result[i - startIndex] = yearBytes[i];
}
return string(result);
}
/**
* @dev Internal function to get the month abbreviation.
* @return The month abbreviation.
*/
function _getMonthFormatted(uint256 month) internal pure returns(string memory) {
if (month == 1) {
return "JAN";
} else if (month == 2) {
return "FEB";
} else if (month == 3) {
return "MAR";
} else if (month == 4) {
return "APR";
} else if (month == 5) {
return "MAY";
} else if (month == 6) {
return "JUN";
} else if (month == 7) {
return "JUL";
} else if (month == 8) {
return "AUG";
} else if (month == 9) {
return "SEP";
} else if (month == 10) {
return "OCT";
} else if (month == 11) {
return "NOV";
} else if (month == 12) {
return "DEC";
} else {
return "INVALID";
}
}
/**
* @dev Internal function to get the number with 2 characters.
* @return The 2 characters for the number.
*/
function _getNumberWithTwoCaracters(uint256 number) internal pure returns(string memory) {
string memory _string = Strings.toString(number);
if (number < 10) {
return string(abi.encodePacked("0", _string));
} else {
return _string;
}
}
/**
* @dev Internal function to get the strike price formatted.
* @return The strike price formatted.
*/
function _getFormattedStrikePrice() internal view returns(string memory) {
uint256 digits;
uint256 count;
int256 representativeAt = -1;
uint256 addPointAt = 0;
uint256 temp = strikePrice;
uint256 number = strikePrice;
while (temp != 0) {
if (representativeAt == -1 && (temp % 10 != 0 || count == uint256(strikeAssetDecimals))) {
representativeAt = int256(digits);
number = temp;
}
if (representativeAt >= 0) {
if (count == uint256(strikeAssetDecimals)) {
addPointAt = digits;
}
digits++;
}
temp /= 10;
count++;
}
if (count <= uint256(strikeAssetDecimals)) {
digits = digits + 2 + uint256(strikeAssetDecimals) - count;
addPointAt = digits - 2;
} else if (addPointAt > 0) {
digits++;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = number;
for (uint256 i = 0; i < digits; ++i) {
if (i > 0 && i == addPointAt) {
buffer[index--] = byte(".");
} else if (number == 0) {
buffer[index--] = byte("0");
} else {
if (representativeAt <= int256(i)) {
buffer[index--] = byte(uint8(48 + number % 10));
}
number /= 10;
}
}
return string(buffer);
}
/**
* @dev Internal function to the asset decimals.
* @param asset Address of the asset.
* @return The asset decimals.
*/
function _getAssetDecimals(address asset) internal view returns(uint8) {
if (_isEther(asset)) {
return uint8(18);
} else {
(bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("decimals()"));
require(success, "ACOToken::_getAssetDecimals: Invalid asset decimals");
return abi.decode(returndata, (uint8));
}
}
/**
* @dev Internal function to the asset symbol.
* @param asset Address of the asset.
* @return The asset symbol.
*/
function _getAssetSymbol(address asset) internal view returns(string memory) {
if (_isEther(asset)) {
return "ETH";
} else {
(bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("symbol()"));
require(success, "ACOToken::_getAssetSymbol: Invalid asset symbol");
return abi.decode(returndata, (string));
}
}
} | Internal function to get the amount of assignable token from an account. account Address of the account. return The assignable amount of tokens./ | function _getAssignableAmount(address account) internal view returns(uint256) {
if (tokenData[account].amount > balanceOf(account)) {
return tokenData[account].amount.sub(balanceOf(account));
return 0;
}
}
| 568,872 |
./partial_match/3/0xa269107FF4a5046CB07A48bB088b006Eae7E8f3C/sources/RecoverToken.sol | Function to set the Cost of the forced "Distribution"////Convert to Wei first!// | function setForceCost(uint costinwei,bool riskypool) public onlyOwner{
if(riskypool == true){
forceriskycost = costinwei;
}
if(riskypool == false)
{
forcesafecost = costinwei;
}
}
| 5,119,256 |
// SPDX-License-Identifier: MIT
// Scroll down to the bottom to find the contract of interest.
// File: @openzeppelin/[email protected]/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/[email protected]/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/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;
}
// File: @openzeppelin/[email protected]/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/[email protected]/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/token/ERC721/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);
}
// File: @openzeppelin/[email protected]/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/[email protected]/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/[email protected]/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/[email protected]/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/utils/introspection/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;
}
}
// File: @openzeppelin/[email protected]/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/token/ERC721/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);
}
// File: @openzeppelin/[email protected]/access/Ownable.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/[email protected]/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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: bd/contracts/SDA.optimized.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/token/ERC721/IERC721.sol";
// import "@openzeppelin/[email protected]/token/ERC721/IERC721Receiver.sol";
// import "@openzeppelin/[email protected]/token/ERC721/extensions/IERC721Metadata.sol";
// import "@openzeppelin/[email protected]/utils/Address.sol";
// import "@openzeppelin/[email protected]/utils/Context.sol";
// import "@openzeppelin/[email protected]/utils/Strings.sol";
// import "@openzeppelin/[email protected]/utils/introspection/ERC165.sol";
/**
* This is a modified version of the ERC721 class, where we only store
* the address of the minter into an _owners array upon minting.
*
* While this saves on minting gas costs, it means that the the balanceOf
* function needs to do a bruteforce search through all the tokens.
*
* For small amounts of tokens (e.g. 8888), RPC services like Infura
* can still query the function.
*
* It also means any future contracts that reads the balanceOf function
* in a non-view function will incur a gigantic gas fee.
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
string private _name;
string private _symbol;
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
uint count = 0;
uint n = _owners.length;
for (uint i = 0; i < n; ++i) {
if (owner == _owners[i]) {
++count;
}
}
return count;
}
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;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
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);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
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);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
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);
}
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");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
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));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
pragma solidity ^0.8.0;
// import "@openzeppelin/[email protected]/token/ERC721/extensions/IERC721Enumerable.sol";
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256 tokenId) {
uint256 count = 0;
uint256 n = _owners.length;
for (uint256 i = 0; i < n; ++i) {
if (owner == _owners[i]) {
if (count == index) {
return i;
} else {
++count;
}
}
}
require(false, "Token not found.");
}
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "Token not found.");
return index;
}
}
pragma solidity ^0.8.0;
pragma abicoder v2;
// import "@openzeppelin/[email protected]/access/Ownable.sol";
// import "@openzeppelin/[email protected]/security/ReentrancyGuard.sol";
contract SorasDreamworldLucidDreaming is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint;
uint public constant TOKEN_PRICE = 80000000000000000; // 0.08 ETH
uint public constant PRE_SALE_TOKEN_PRICE = 50000000000000000; // 0.05 ETH
uint public constant MAX_TOKENS_PER_PUBLIC_MINT = 10; // Only applies during public sale.
uint public constant MAX_TOKENS = 8888;
address public constant GENESIS_BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
/// @dev 1: presale, 2: public sale, 3: genesis claim, 4: genesis burn, 255: closed.
uint public saleState;
/// @dev A mapping of the token names.
mapping(uint => string) public tokenNames;
// @dev Whether the presale slot has been used. One slot per address.
mapping(address => bool) public presaleUsed;
/// @dev 256-bit words, each representing 256 booleans.
mapping(uint => uint) internal genesisClaimedMap;
/// @dev The license text/url for every token.
string public LICENSE = "https://www.nftlicense.org";
/// @dev Link to a Chainrand NFT.
/// This contains all the information needed to reproduce
/// the traits with a locked Chainlink VRF result.
string public PROVENANCE;
/// @dev The base URI
string public baseURI;
event TokenNameChanged(address _by, uint _tokenId, string _name);
event LicenseSet(string _license);
event ProvenanceSet(string _provenance);
event SaleClosed();
event PreSaleOpened();
event PublicSaleOpened();
event GenesisClaimOpened();
event GenesisBurnOpened();
// IMPORTANT: Make sure to change this to the correct address before publishing!
// Gen 0 mainnet address: 0x4e2781e3aD94b2DfcF34c51De0D8e9358c69F296
IERC721 internal genesisContract = IERC721(0x4e2781e3aD94b2DfcF34c51De0D8e9358c69F296);
constructor()
ERC721("Sora's Dreamworld: LUCID DREAMING", "SDLD") {
saleState = 255;
baseURI = "https://sorasdreamworld.io/tokens/dark/";
}
/// @dev Withdraws Ether for the owner.
function withdraw() public onlyOwner {
uint256 amount = address(this).balance;
payable(msg.sender).transfer(amount);
}
/// @dev Sets the provenance.
function setProvenance(string memory _provenance) public onlyOwner {
PROVENANCE = _provenance;
emit ProvenanceSet(_provenance);
}
/// @dev Sets base URI for all token IDs.
/// e.g. https://sorasdreamworld.io/tokens/dark/
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
/// @dev Open the pre-sale.
function openPreSale() public onlyOwner {
saleState = 1;
emit PreSaleOpened();
}
/// @dev Open the public sale.
function openPublicSale() public onlyOwner {
saleState = 2;
emit PublicSaleOpened();
}
/// @dev Open the claim phase.
function openGenesisClaim() public onlyOwner {
saleState = 3;
emit GenesisClaimOpened();
}
/// @dev Open the burn phase.
function openGenesisBurn() public onlyOwner {
saleState = 4;
emit GenesisBurnOpened();
}
/// @dev Close the sale.
function closeSale() public onlyOwner {
saleState = 255;
emit SaleClosed();
}
/// @dev Mint just one NFT.
function mintOne(address _toAddress) internal {
uint mintIndex = totalSupply();
require(mintIndex < MAX_TOKENS, "Sold out.");
_safeMint(_toAddress, mintIndex);
}
/// @dev Force mint for the addresses.
// Can be called anytime.
// If called right after the creation of the contract, the tokens
// are assigned sequentially starting from id 0.
function forceMint(address[] memory _addresses) public onlyOwner {
for (uint i = 0; i < _addresses.length; ++i) {
mintOne(_addresses[i]);
}
}
/// @dev Self mint for the owner.
/// Can be called anytime.
/// This does not require the sale to be open.
function selfMint(uint _numTokens) public onlyOwner {
for (uint i = 0; i < _numTokens; ++i) {
mintOne(msg.sender);
}
}
/// @dev Sets the license text.
function setLicense(string memory _license) public onlyOwner {
LICENSE = _license;
emit LicenseSet(_license);
}
/// @dev Returns the license for tokens.
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "Token not found.");
return LICENSE;
}
/// @dev Mints tokens.
function mint(uint _numTokens) public payable nonReentrant {
// saleState == 1 || saleState == 2. Zero is not used.
require(saleState < 3, "Not open.");
require(_numTokens > 0, "Minimum number to mint is 1.");
address sender = msg.sender;
uint effectiveTokenPrice;
if (saleState == 1) {
effectiveTokenPrice = PRE_SALE_TOKEN_PRICE;
require(_numTokens <= 1, "Number per mint exceeded.");
require(genesisContract.balanceOf(sender) > 0, "You don't have a Dream Machine.");
require(!presaleUsed[sender], "Presale slot already used.");
presaleUsed[sender] = true;
} else { // 2
effectiveTokenPrice = TOKEN_PRICE;
require(_numTokens <= MAX_TOKENS_PER_PUBLIC_MINT, "Number per mint exceeded.");
}
require(msg.value >= effectiveTokenPrice * _numTokens, "Wrong Ether value.");
for (uint i = 0; i < _numTokens; ++i) {
mintOne(sender);
}
}
/// @dev Returns whether the genesis token has been claimed.
function checkGenesisClaimed(uint _genesisId) public view returns(bool) {
uint t = _genesisId;
uint q = t >> 8;
uint r = t & 255;
uint m = genesisClaimedMap[q];
return m & (1 << r) != 0;
}
/// @dev Returns an array of uints representing whether the token has been claimed.
function genesisClaimed(uint[] memory _genesisIds) public view returns(bool[] memory) {
uint n = _genesisIds.length;
bool[] memory a = new bool[](n);
for (uint i = 0; i < n; ++i) {
a[i] = checkGenesisClaimed(_genesisIds[i]);
}
return a;
}
/// @dev Use the genesis tokens to claim free mints.
function genesisClaim(uint[] memory _genesisIds) public nonReentrant {
require(saleState == 3, "Not open.");
uint n = _genesisIds.length;
require(n > 0 && n % 3 == 0, "Please submit a positive multiple of 3.");
address sender = msg.sender;
uint qPrevInitial = 1 << 255;
uint qPrev = qPrevInitial;
uint m;
for (uint i = 0; i < n; i += 3) {
for (uint j = 0; j < 3; ++j) {
uint t = _genesisIds[i + j];
uint q = t >> 8;
uint r = t & 255;
if (q != qPrev) {
if (qPrev != qPrevInitial) {
genesisClaimedMap[qPrev] = m;
}
m = genesisClaimedMap[q];
}
qPrev = q;
uint b = 1 << r;
// Token must be unused and owned.
require(m & b == 0 && genesisContract.ownerOf(t) == sender, "Invalid submission.");
// Modifying the map and checking will ensure that there
// are no duplicates in _genesisIds.
m = m | b;
}
mintOne(sender);
}
genesisClaimedMap[qPrev] = m;
}
/// @dev Burns the genesis tokens for free mints.
function genesisBurn(uint[] memory _genesisIds) public nonReentrant {
require(saleState == 4, "Not open.");
uint n = _genesisIds.length;
require(n > 0 && n & 1 == 0, "Please submit a positive multiple of 2.");
address sender = msg.sender;
for (uint i = 0; i < n; i += 2) {
// Transfer from requires that the token must be owned.
// Calling it in sequence will ensure that no are no
// duplicates in _genesisIds.
genesisContract.transferFrom(sender, GENESIS_BURN_ADDRESS, _genesisIds[i]);
genesisContract.transferFrom(sender, GENESIS_BURN_ADDRESS, _genesisIds[i + 1]);
mintOne(sender);
}
}
/// @dev Returns an array of the token ids under the owner.
function tokensOfOwner(address _owner) external view returns (uint[] memory) {
uint[] memory a = new uint[](balanceOf(_owner));
uint j = 0;
uint n = _owners.length;
for (uint i; i < n; ++i) {
if (_owner == _owners[i]) {
a[j++] = i;
}
}
return a;
}
/// @dev Change the token name.
function changeTokenName(uint _id, string memory _name) public {
require(ownerOf(_id) == msg.sender, "You do not own this token.");
require(sha256(bytes(_name)) != sha256(bytes(tokenNames[_id])), "Name unchanged.");
tokenNames[_id] = _name;
emit TokenNameChanged(msg.sender, _id, _name);
}
/// @dev Returns the token's URI for the metadata.
function tokenURI(uint256 _id) public view virtual override returns (string memory) {
require(_id < totalSupply(), "Token not found.");
return string(abi.encodePacked(baseURI, _id.toString()));
}
/// @dev Returns the most relevant stats in a single go to reduce RPC calls.
function stats() external view returns (uint[] memory) {
uint[] memory a = new uint[](4);
a[0] = saleState;
a[1] = totalSupply();
a[2] = genesisContract.balanceOf(GENESIS_BURN_ADDRESS);
a[3] = saleState == 1 ? PRE_SALE_TOKEN_PRICE : TOKEN_PRICE;
return a;
}
} | Force mint for the addresses. Can be called anytime. If called right after the creation of the contract, the tokens are assigned sequentially starting from id 0. | function forceMint(address[] memory _addresses) public onlyOwner {
for (uint i = 0; i < _addresses.length; ++i) {
mintOne(_addresses[i]);
}
}
| 102,164 |
./partial_match/1/0x98058d3A8336Fb53A91312b6f2c4E0Fe0e988eab/sources/FULUSHOU.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Fu Lu Shou", "FU") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyCharityFee = 0;
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 23;
uint256 _sellCharityFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 23;
uint256 totalSupply = 777777777777777 * 1e18;
buyCharityFee = _buyCharityFee;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
sellCharityFee = _sellCharityFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,571,312 |
pragma solidity ^0.5.12;
pragma experimental ABIEncoderV2;
/*-
* Copyright (c) 2019 @secondphonejune
* All rights reserved.
*
* This code is derived by @secondphonejune (Telegram ID)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* This project is originally created to implement an election for 2019 Hong Kong local elections.
* Ofcause the Hong Kong government is not going to use it, but we have a chance to show that how an election can be done completely anonymously with blockchain
* Everyone can use the code provided in this project, but they must keep this statement here unchanged.
* Fight for freedom, Stand with Hong Kong
* Five Demands, Not One Less
*/
/*
* Expected workflow, voter get his/her voter ID from contract, this makes sure no one has access to his/her personal data
* Second, the voter registers their voter ID and email (not phone as no money to do SMS) via a vote box and make a vote.
* Email is checked by the voter box to prevent double voting and robot voting, but there should be a better way to do it.
* Now registration will make old registration and votes from the same voter ID invalid
* The vote will then encrypted using a public key and submitted to this contract for record
* After the election, the private key will be made public and people can decrypt the votes and knows who wins
* Currently we let the vote box decides if a new vote should replace the old vote, but there should be a better way to do it
* Also if people can read the private variable voteListByVoter from blockchain, they will know who a person votes after election.
* The variable is needed for replacing old votes.
* This variable should be removed when there is a proper way to authenticate a person and replacing vote is not needed.
*/
contract electionList{
string public hashHead;
//This one keeps the council list for easy checking by public
string[] public councilList;
uint256 public councilNumber;
}
contract localElection{
address payable public owner;
string public encryptionPublicKey; //Just keep record on the vote encryption key
bool public isRunningElection = false;
//vote box exists only because most people do not own a crypto account.
//vote box are needed to encrypt and submit votes for people and do email validations
//Once the election is over, vote box also need to get votes from the contract and decrypt the votes
mapping(address => bool) public approvedVoteBox;
//This one is dummy list as the voter list is hidden from public
//Even in real case, this one only keeps the hash of the voter information, so no private data is leaked
//With the same name and HKID (voter), a person can only vote in one council
//The following information is created and verified by government before the election,
//but in this 2019 election even voter list is hidden from people.
//We setup register function for people to register just before they vote
mapping(uint256 => bool) public voterList;
mapping(uint256 => uint256) public usedPhoneNumber;
mapping(uint256 => mapping(string => bool)) public councilVoterList;
mapping(string => uint) public councilVoterNumber;
//This one keeps the votes, but arranged by voter so it is easy to check if someone has voted
//This file must be kept private as it links a person to a vote,
//people can find back who a person voted after the election
//If there is an electronic way for public to really verify a person to do the voting,
//there will be no need to setup replaceVote function.
//We can safely remove the link between vote and voter
mapping(uint256 => string) private voteListByVoter;
mapping(string => string[]) private votes; //Votes grouped by council
mapping(address => string[]) private voteByVotebox; //Votes grouped by votebox
mapping(string => bool) private voteDictionary; //Makre sure votes are unique
mapping(string => address) public invalidVotes;
address public dbAddress;
constructor(address electionDBaddr,string memory pKey) public{
owner = msg.sender;
dbAddress = electionDBaddr;
encryptionPublicKey = pKey;
}
function() external payable {
//Thank you for donation, it will be sent to the owner.
//The owner will send it to 星火 after deducting the cost (if they have ETH account)
if(address(this).balance >= msg.value && msg.value >0)
owner.transfer(msg.value);
}
//Just in case someone manage to give ETH to this contract
function withdrawAll() public payable{
if(address(this).balance >0) owner.transfer(address(this).balance);
}
function addVoteBox(address box) public {
if(msg.sender != owner) revert();
approvedVoteBox[box] = true;
}
function removeVoteBox(address box) public {
if(msg.sender != owner) revert();
approvedVoteBox[box] = false;
//Also remove all votes in that votebox from the election result
electionList db = electionList(dbAddress);
for(uint i=0;i<db.councilNumber();i++){
for(uint a=0;a<voteByVotebox[box].length;a++){
if(bytes(voteByVotebox[box][a]).length >0){
invalidVotes[voteByVotebox[box][a]] = msg.sender;
}
}
}
}
function getVoteboxVoteCount(address box) public view returns(uint256){
return voteByVotebox[box].length;
}
function getCouncilVoteCount(string memory council) public view returns(uint256){
return votes[council].length;
}
function startElection() public {
if(msg.sender != owner) revert();
isRunningElection = true;
}
function stopElection() public {
if(msg.sender != owner) revert();
isRunningElection = false;
}
//This function allows people to generate a voterID to register and vote.
//Supposingly this ID should be random so that people do not know who it belongs to,
//and each person has only one unique ID so they cannot double vote.
//It means a public key pair binding with identity / hash of identity.
//As most people do not have a wallet, we can only make sure each person has one ID only
function getVoterID(string memory name, string memory HKID)
public view returns(uint256){
electionList db = electionList(dbAddress);
if(!checkHKID(HKID)) return 0;
return uint256(sha256(joinStrToBytes(db.hashHead(),name,HKID)));
}
//function getphoneHash(uint number)
function getEmailHash(string memory email)
public view returns(uint256){
//return uint256(sha256(joinStrToBytes(hashHead,uint2str(number),"")));
electionList db = electionList(dbAddress);
return uint256(sha256(joinStrToBytes(db.hashHead(),email,"")));
}
//function register(uint256 voterID, uint256 hashedPhone, string memory council)
function register(uint256 voterID, uint256 hashedEmail, string memory council)
public returns(bool){
require(isRunningElection);
require(approvedVoteBox[msg.sender]);
//Register happens during election as we do not have the voter list
//require(now >= votingStartTime);
//require(now < votingEndTime);
if(voterList[voterID]) deregister(voterID);
//if(usedPhoneNumber[hashedPhone] > 0)
//deregister(usedPhoneNumber[hashedPhone]);
if(usedPhoneNumber[hashedEmail] > 0)
deregister(usedPhoneNumber[hashedEmail]);
voterList[voterID] = true;
//usedPhoneNumber[hashedPhone] = voterID;
usedPhoneNumber[hashedEmail] = voterID;
councilVoterList[voterID][council] = true;
councilVoterNumber[council]++;
return true;
}
function deregister(uint256 voterID)
internal returns(bool){
require(isRunningElection);
voterList[voterID] = false;
electionList db = electionList(dbAddress);
for(uint i=0;i<db.councilNumber();i++){
//deregister them from the other councils
if(councilVoterList[voterID][db.councilList(i)]){
councilVoterList[voterID][db.councilList(i)] = false;
councilVoterNumber[db.councilList(i)]--;
}
}
if(bytes(voteListByVoter[voterID]).length >0){
invalidVotes[voteListByVoter[voterID]] = msg.sender;
delete voteListByVoter[voterID];
}
return true;
}
//function isValidVoter(uint256 voterID, uint256 hashedPhone, string memory council)
function isValidVoter(uint256 voterID, uint256 hashedEmail, string memory council)
public view returns(bool){
if(!voterList[voterID]) return false;
//if(usedPhoneNumber[hashedPhone] == 0 || usedPhoneNumber[hashedPhone] != voterID)
if(usedPhoneNumber[hashedEmail] == 0 || usedPhoneNumber[hashedEmail] != voterID)
return false;
if(!councilVoterList[voterID][council]) return false;
return true;
}
function isVoted(uint256 voterID) public view returns(bool){
if(bytes(voteListByVoter[voterID]).length >0) return true;
return false;
}
//function submitVote(uint256 voterID, uint256 hashedPhone,
function submitVote(uint256 voterID, uint256 hashedEmail,
string memory council, string memory singleVote) public returns(bool){
require(isRunningElection);
require(approvedVoteBox[msg.sender]);
//require(now >= votingStartTime);
//require(now < votingEndTime);
//require(isValidVoter(voterID,hashedPhone,council));
require(isValidVoter(voterID,hashedEmail,council));
require(!isVoted(voterID)); //Voted already
require(!voteDictionary[singleVote]);
voteListByVoter[voterID] = singleVote;
votes[council].push(singleVote);
voteByVotebox[msg.sender].push(singleVote);
voteDictionary[singleVote] = true;
return true;
}
//function replaceVote(uint256 voterID, uint256 hashedPhone,
/*function replaceVote(uint256 voterID, uint256 hashedEmail,
string memory council, string memory singleVote) public returns(bool){
require(isRunningElection);
require(approvedVoteBox[msg.sender]);
//require(now >= votingStartTime);
//require(now < votingEndTime);
//require(isValidVoter(voterID,hashedPhone,council));
require(isValidVoter(voterID,hashedEmail,council));
require(!voteDictionary[singleVote]);
if(bytes(voteListByVoter[voterID]).length >0){
electionList db = electionList(dbAddress);
for(uint i=0;i<db.councilNumber();i++){
//reduce the vote count in the previous council
if(councilVoterList[voterID][db.councilList(i)]){
councilVoteCount[db.councilList(i)]--;
}
}
invalidVotes[voteListByVoter[voterID]] = msg.sender;
delete voteListByVoter[voterID];
}
voteListByVoter[voterID] = singleVote;
votes[council].push(singleVote);
councilVoteCount[council]++;
voteDictionary[singleVote] = true;
return true;
}*/
function registerAndVote(uint256 voterID, uint256 hashedEmail,
string memory council, string memory singleVote) public returns(bool){
if(register(voterID,hashedEmail,council)
&& submitVote(voterID,hashedEmail,council,singleVote))
return true;
return false;
}
function getResult(string memory council) public view returns(uint, uint, uint, uint,
string[] memory, string[] memory){
require(!isRunningElection);
//require(now >= votingEndTime);
uint totalVoteCount = votes[council].length;
uint validVoteCount;
//uint invalidCount;
for(uint i=0;i<totalVoteCount;i++){
string memory singleVote = votes[council][i];
if(invalidVotes[singleVote] == address(0)){
validVoteCount++;
}
//else invalidCount++;
}
//assert((validVoteCount+invalidCount) == totalVoteCount);
string[] memory validVoteIndex = new string[](validVoteCount);
string[] memory invalidVoteIndex = new string[](totalVoteCount-validVoteCount);
uint a=0;
for(uint i=0;i<totalVoteCount && (a<validVoteCount || validVoteCount==0);i++){
string memory singleVote = votes[council][i];
if(invalidVotes[singleVote] == address(0)){
validVoteIndex[a++] = singleVote;
}else{
invalidVoteIndex[i-a] = singleVote;
}
}
return (councilVoterNumber[council],totalVoteCount,validVoteCount,
totalVoteCount-validVoteCount,validVoteIndex,invalidVoteIndex);
}
function joinStrToBytes(string memory _a, string memory _b, string memory _c)
internal pure returns (bytes memory){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory ab = new string(_ba.length + _bb.length + _bc.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) bab[k++] = _bc[i];
//return string(bab);
return bab;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
//Sample G123456A AB9876543, C1234569 invalid sample AY987654A C668668E
function checkHKID(string memory HKID)
internal pure returns(bool){
bytes memory b = bytes(HKID);
if(b.length !=8 && b.length !=9) return false;
uint256 checkDigit = 0;
uint256 power = 9;
if(b.length ==8){
checkDigit += (36*power);
power--;
}
for(uint i=0;i<b.length;i++){
uint digit = uint8(b[i]);
if(i>(b.length-8) && i<(b.length-1)){
//It should be a number
if(digit < 48 || digit > 57) return false;
}
if(digit >=48 && digit<=57) checkDigit += ((digit-48)*power); //Number
else if(digit >=65 && digit<=90) checkDigit += ((digit-55)*power); //A-Z
else return false;
power--;
}
if(checkDigit % 11 == 0) return true;
return false;
}
} | function isValidVoter(uint256 voterID, uint256 hashedPhone, string memory council)if(usedPhoneNumber[hashedPhone] == 0 || usedPhoneNumber[hashedPhone] != voterID) | function isValidVoter(uint256 voterID, uint256 hashedEmail, string memory council)
public view returns(bool){
if(!voterList[voterID]) return false;
if(usedPhoneNumber[hashedEmail] == 0 || usedPhoneNumber[hashedEmail] != voterID)
return false;
if(!councilVoterList[voterID][council]) return false;
return true;
}
| 7,293,105 |
./partial_match/42/0xb1ae3AC28a49F8fbbE2C4c5826d5B36327A77497/sources/CeresTestPresaleStage1.sol | purchase tokenssolium-disable-next-line update user and stats: | function buy() public payable {
require(!paused, "presale is paused");
require(msg.value >= minimum, "amount too small");
require(weiRaised.add(msg.value) <= cap, "cap hit");
uint256 amount = calculateAmountPurchased(msg.value);
uint256 potentialAmount = investors[msg.sender].ceresBalance.add(amount);
require(totalOwed.add(amount) <= ceresTest.balanceOf(address(this)), "sold out");
require(potentialAmount.mul(price).div(1e18) <= maximum, "maximum purchase cap hit");
investors[msg.sender].ceresBalance = potentialAmount;
investors[msg.sender].percent20 = potentialAmount * 2000 / BPS;
investors[msg.sender].periods = [0, 0, 0, 0, 0];
totalOwed = totalOwed.add(amount);
weiRaised = weiRaised.add(msg.value);
}
| 3,303,989 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./Context.sol";
import "./Ownable.sol";
/**
* @dev
*/
abstract contract Approve is Context, Ownable {
address private _approver;
bool public isApproved;
event NewApprover(address indexed previousApprover, address indexed newApprover);
/**
* @dev Throws if approval is not given or sender is not owner
*/
modifier onlyOwnerWithApproval() {
require(isApproved, "No approval given");
require(owner() == _msgSender(), "Caller is not the owner");
_;
isApproved = false;
}
/**
* @dev Throws if sender is not appover
*/
modifier onlyApprover() {
require(_approver == _msgSender(), "Caller is not the approver");
_;
}
/**
* @dev Initializes the contract
*/
constructor() {
address msgSender = _msgSender();
_approver = msgSender;
}
/**
* @dev Returns the address of the current approver.
*/
function approver() public view returns (address) {
return _approver;
}
/**
* @dev Approve
*/
function grantApproval() public {
require(_msgSender() == _approver, "Not allowed to approve");
require(!isApproved, "Approval already given");
isApproved = true;
}
/**
* @dev Remove approval
*/
function removeApproval() public {
require(_msgSender() == _approver, "Not allowed to approve");
require(isApproved, "No approval given");
isApproved = false;
}
/**
* @dev Transfers approver of the contract to a new account (`newApprover`).
* Can only be called by the current owner.
*/
function transferApprover(address newApprover) public onlyApprover {
_transferApprover(newApprover);
}
/**
* @dev Transfers approver of the contract to a new account (`newApprover`).
*/
function _transferApprover(address newApprover) internal {
require(newApprover != address(0), 'New approver is the zero address');
emit NewApprover(_approver, newApprover);
_approver = newApprover;
}
} | Remove approval/ | function removeApproval() public {
require(_msgSender() == _approver, "Not allowed to approve");
require(isApproved, "No approval given");
isApproved = false;
}
| 13,118,148 |
pragma solidity ^0.4.0;
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
}
contract Resolver {
function setAddr(bytes32 nodeHash, address addr);
}
contract ReverseRegistrar {
function claim(address owner) returns (bytes32 node);
}
/**
* FireflyRegistrar
*
* This registrar allows arbitrary labels below the root node for a fixed minimum fee.
* Labels must conform to the regex /^[a-z0-9-]{4, 20}$/.
*
* Admin priviledges:
* - change the admin
* - change the fee
* - change the default resolver
* - withdrawl funds
*
* This resolver should is designed to be self-contained, so that in the future
* switching to a new Resolver should not impact this one.
*
*/
contract FireflyRegistrar {
// namehash('addr.reverse')
bytes32 constant RR_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// Admin triggered events
event adminChanged(address oldAdmin, address newAdmin);
event feeChanged(uint256 oldFee, uint256 newFee);
event defaultResolverChanged(address oldResolver, address newResolver);
event didWithdraw(address target, uint256 amount);
// Registration
event nameRegistered(bytes32 indexed nodeHash, address owner, uint256 fee);
// Donations
event donation(bytes32 indexed nodeHash, uint256 amount);
AbstractENS _ens;
Resolver _defaultResolver;
address _admin;
bytes32 _nodeHash;
uint256 _fee;
uint256 _totalPaid = 0;
uint256 _nameCount = 0;
mapping (bytes32 => uint256) _donations;
function FireflyRegistrar(address ens, bytes32 nodeHash, address defaultResolver) {
_ens = AbstractENS(ens);
_nodeHash = nodeHash;
_defaultResolver = Resolver(defaultResolver);
_admin = msg.sender;
_fee = 0.1 ether;
// Give the admin access to the reverse entry
ReverseRegistrar(_ens.owner(RR_NODE)).claim(_admin);
}
/**
* setAdmin(admin)
*
* Change the admin of this contract. This should be used shortly after
* deployment and live testing to switch to a multi-sig contract.
*/
function setAdmin(address admin) {
if (msg.sender != _admin) { throw; }
adminChanged(_admin, admin);
_admin = admin;
// Give the admin access to the reverse entry
ReverseRegistrar(_ens.owner(RR_NODE)).claim(admin);
// Point the resolved addr to the new admin
Resolver(_ens.resolver(_nodeHash)).setAddr(_nodeHash, _admin);
}
/**
* setFee(fee)
*
* This is useful if the price of ether sky-rockets or plummets, but
* for the most part should remain unused
*/
function setFee(uint256 fee) {
if (msg.sender != _admin) { throw; }
feeChanged(_fee, fee);
_fee = fee;
}
/**
* setDefaultResolver(resolver)
*
* Allow the admin to change the default resolver that is setup with
* new name registrations.
*/
function setDefaultResolver(address defaultResolver) {
if (msg.sender != _admin) { throw; }
defaultResolverChanged(_defaultResolver, defaultResolver);
_defaultResolver = Resolver(defaultResolver);
}
/**
* withdraw(target, amount)
*
* Allow the admin to withdrawl funds.
*/
function withdraw(address target, uint256 amount) {
if (msg.sender != _admin) { throw; }
if (!target.send(amount)) { throw; }
didWithdraw(target, amount);
}
/**
* register(label)
*
* Allows anyone to send *fee* ether to the contract with a name to register.
*
* Note: A name must match the regex /^[a-z0-9-]{4,20}$/
*/
function register(string label) payable {
// Check the label is legal
uint256 position;
uint256 length;
assembly {
// The first word of a string is its length
length := mload(label)
// The first character position is the beginning of the second word
position := add(label, 1)
}
// Labels must be at least 4 characters and at most 20 characters
if (length < 4 || length > 20) { throw; }
// Only allow /^[a-z0-9-]*$/
for (uint256 i = 0; i < length; i++) {
uint8 c;
assembly { c := and(mload(position), 0xFF) }
// 'a' 'z' '0' '9' '-'
if ((c < 0x61 || c > 0x7a) && (c < 0x30 || c > 0x39) && c != 0x2d) {
throw;
}
position++;
}
// Paid too little; participants may pay more (as a donation)
if (msg.value < _fee) { throw; }
// Compute the label and node hash
var labelHash = sha3(label);
var nodeHash = sha3(_nodeHash, labelHash);
// This is already owned in ENS
if (_ens.owner(nodeHash) != address(0)) { throw; }
// Make this registrar the owner (so we can set it up before giving it away)
_ens.setSubnodeOwner(_nodeHash, labelHash, this);
// Set up the default resolver and point to the sender
_ens.setResolver(nodeHash, _defaultResolver);
_defaultResolver.setAddr(nodeHash, msg.sender);
// Now give it to the sender
_ens.setOwner(nodeHash, msg.sender);
_totalPaid += msg.value;
_nameCount++;
_donations[nodeHash] += msg.value;
nameRegistered(nodeHash, msg.sender, msg.value);
donation(nodeHash, msg.value);
}
/**
* donate(nodeHash)
*
* Allow a registered name to donate more and get attribution. This may
* be useful if special limited edition Firefly devices are awarded to
* certain tiers of donors or such.
*/
function donate(bytes32 nodeHash) payable {
_donations[nodeHash] += msg.value;
donation(nodeHash, msg.value);
}
/**
* config()
*
* Get the configuration of this registrar.
*/
function config() constant returns (address ens, bytes32 nodeHash, address admin, uint256 fee, address defaultResolver) {
ens = _ens;
nodeHash = _nodeHash;
admin = _admin;
fee = _fee;
defaultResolver = _defaultResolver;
}
/**
* stats()
*
* Get some statistics for this registrar.
*/
function stats() constant returns (uint256 nameCount, uint256 totalPaid, uint256 balance) {
nameCount = _nameCount;
totalPaid = _totalPaid;
balance = this.balance;
}
/**
* donations(nodeHash)
*
* Returns the amount of donations a nodeHash has provided.
*/
function donations(bytes32 nodeHash) constant returns (uint256 donation) {
return _donations[nodeHash];
}
/**
* fee()
*
* The current fee forregistering a name.
*/
function fee() constant returns (uint256 fee) {
return _fee;
}
/**
* Allow anonymous donations.
*/
function () payable {
_donations[0] += msg.value;
donation(0, msg.value);
}
} | Allow anonymous donations./ | function () payable {
_donations[0] += msg.value;
donation(0, msg.value);
}
| 1,836,161 |
pragma solidity ^0.5;
// solhint-disable-next-line
import './base/openzeppelin/math/SafeMath.sol';
import './base/bancor/BancorFormula.sol';
import './Uninitialized.sol';
import './IMarket.sol';
import './Restricted.sol';
import './Macros.sol';
// #def ONE_DAY 24 * 60 * 60
// #if TEST
// #def BLOCKTIME _blockTime
// #else
// #def BLOCKTIME uint64(block.timestamp)
// #endif
/// @title Contract that manages buying, selling, minting, burning, and
/// moving of Upcity resource tokens.
/// @author Lawrence Forman ([email protected])
contract UpcityMarket is BancorFormula, Uninitialized, Restricted, IMarket {
using SafeMath for uint256;
address private constant ZERO_ADDRESS = address(0x0);
// 100% or 1.0 in parts per million.
uint32 private constant PPM_ONE = $$(1e6);
// The bancor connector weight, which determines price evolution, in ppm.
uint32 private constant CONNECTOR_WEIGHT = $$(int(CONNECTOR_WEIGHT * 1e6));
// State for each resource token.
struct Token {
// The number of tokens minted, in wei.
uint256 supply;
// The ether balance for this resource.
uint256 funds;
// Stashed tokens that will be used to fill mint operations until depleted.
uint256 stash;
// Price yesterday.
uint256 priceYesterday;
// The canonical index of this token.
uint8 idx;
// The address of the token contract.
address token;
// The balances of each address.
mapping(address=>uint256) balances;
}
// @dev When the priceYesterday of each token was last updated.
uint64 public yesterday;
// Indiividual states for each resource token.
mapping(address=>Token) private _tokens;
// Token addresses for each resource token.
address[NUM_RESOURCES] private _tokenAddresses;
/// @dev Raised whenever resource tokens are bought.
/// @param resource The address of the token/resource.
/// @param to The recepient of the tokens.
/// @param value The ether value of the tokens.
/// @param bought The number of tokens bought.
event Bought(
address indexed resource,
address indexed to,
uint256 value,
uint256 bought);
/// @dev Raised whenever resource tokens are sold.
/// @param resource The address of the token/resource.
/// @param to The recepient of the ether.
/// @param sold The number of tokens sold.
/// @param value The ether value of the tokens.
event Sold(
address indexed resource,
address indexed to,
uint256 sold,
uint256 value);
/// @dev Raised whenever the market is funded.
/// @param value The amount of ether deposited.
event Funded(uint256 value);
// Only callable by a registered token.
modifier onlyToken() {
require(_tokens[msg.sender].token == msg.sender, ERROR_RESTRICTED);
_;
}
/// @dev Deploy the market.
/// init() needs to be called before market functions will work.
constructor() public {
}
/// @dev Fund the markets.
/// Attached ether will be distributed evenly across all token markets.
function() external payable onlyInitialized {
if (msg.value > 0) {
_touch();
for (uint8 i = 0; i < NUM_RESOURCES; i++) {
Token storage token = _tokens[_tokenAddresses[i]];
token.funds = token.funds.add(msg.value/NUM_RESOURCES);
}
emit Funded(msg.value);
}
}
/// @dev Initialize and fund the markets.
/// This can only be called once by the contract creator.
/// Attached ether will be distributed evenly across all token markets.
/// This will also establish the "canonical order," of tokens.
/// @param supplyLock The amount of each token to mint and lock up immediately.
/// @param tokens The address of each token, in canonical order.
/// @param authorities Address of authorities to register, which are
/// addresses that can mint and burn tokens.
function init(
uint256 supplyLock,
address[NUM_RESOURCES] calldata tokens,
address[] calldata authorities)
external payable onlyCreator onlyUninitialized {
require(msg.value >= NUM_RESOURCES, ERROR_INVALID);
// Set authorities.
for (uint8 i = 0; i < authorities.length; i++)
isAuthority[authorities[i]] = true;
// Initialize token states.
for (uint8 i = 0; i < NUM_RESOURCES; i++) {
address addr = tokens[i];
// Prevent duplicates.
require(_tokens[addr].token == ZERO_ADDRESS, ERROR_INVALID);
_tokenAddresses[i] = addr;
Token storage token = _tokens[addr];
token.token = addr;
token.idx = i;
token.supply = supplyLock;
token.balances[address(this)] = supplyLock;
token.funds = msg.value / NUM_RESOURCES;
token.priceYesterday = _getTokenPrice(
token.funds, supplyLock);
}
yesterday = $(BLOCKTIME);
_bancorInit();
_init();
}
/// @dev Get all token addresses the market supports.
/// @return Array of token addresses.
function getTokens()
external view returns (address[NUM_RESOURCES] memory tokens) {
// #for RES in range(NUM_RESOURCES)
tokens[$$(RES)] = _tokenAddresses[$$(RES)];
// #done
}
/// @dev Get the state of a resource token.
/// @param resource Address of the resource token contract.
/// @return The price, supply, (ether) balance, stash, and yesterday's price
/// for that token.
function describeToken(address resource)
external view returns (
uint256 price,
uint256 supply,
uint256 funds,
uint256 stash,
uint256 priceYesterday) {
Token storage token = _tokens[resource];
require(token.token == resource, ERROR_INVALID);
price = getPrices()[token.idx];
supply = token.supply;
funds = token.funds;
stash = token.stash;
priceYesterday = token.priceYesterday;
}
/// @dev Get the current price of all tokens.
/// @return The price of each resource, in wei, in canonical order.
function getPrices()
public view returns (uint256[NUM_RESOURCES] memory prices) {
// #for RES in range(NUM_RESOURCES)
prices[$(RES)] = _getTokenPrice(
_tokens[_tokenAddresses[$(RES)]].funds,
_tokens[_tokenAddresses[$(RES)]].supply);
// #done
}
/// @dev Get the supply of all tokens.
/// @return The supply of each resource, in wei, in canonical order.
function getSupplies()
external view returns (uint256[NUM_RESOURCES] memory supplies) {
// #for RES in range(NUM_RESOURCES)
supplies[$(RES)] = _tokens[_tokenAddresses[$(RES)]].supply;
// #done
}
/// @dev Get the current supply of a token.
/// @param resource Address of the resource token contract.
/// @return The supply the resource, in wei, in canonical order.
function getSupply(address resource) external view returns (uint256) {
Token storage token = _tokens[resource];
require(resource != ZERO_ADDRESS && token.token == resource,
ERROR_INVALID);
return token.supply;
}
/// @dev Get the balances all tokens for `owner`.
/// @param owner The owner of the tokens.
/// @return The amount of each resource held by `owner`, in wei, in
/// canonical order.
function getBalances(address owner)
external view returns (uint256[NUM_RESOURCES] memory balances) {
// #for RES in range(NUM_RESOURCES)
balances[$(RES)] = _tokens[_tokenAddresses[$(RES)]].balances[owner];
// #done
}
/// @dev Get the balance of a token for `owner`.
/// @param resource Address of the resource token contract.
/// @param owner The owner of the tokens.
/// @return The amount of the given token held by `owner`.
function getBalance(address resource, address owner)
external view returns (uint256) {
Token storage token = _tokens[resource];
require(resource != ZERO_ADDRESS && token.token == resource,
ERROR_INVALID);
return token.balances[owner];
}
/// @dev Transfer a resource tokens between owners.
/// Can only be called by a token contract.
/// The resource/token address is msg.sender.
/// @param from The owner wallet.
/// @param to The receiving wallet
/// @param amount Amount of the token to transfer.
function proxyTransfer(
address from, address to, uint256 amount)
external onlyInitialized onlyToken {
Token storage token = _tokens[msg.sender];
_transfer(token, from, to, amount);
}
/// @dev Tansfer tokens between owners.
/// Can only be called by an authority.
/// @param from The owner wallet.
/// @param to The receiving wallet
/// @param amounts Amount of each token to transfer.
function transfer(
address from, address to, uint256[NUM_RESOURCES] calldata amounts)
external onlyInitialized onlyAuthority {
// #for RES in range(NUM_RESOURCES)
_transfer(_tokens[_tokenAddresses[$(RES)]], from, to, amounts[$(RES)]);
// #done
}
/// @dev Buy tokens with ether.
/// Any overpayment of ether will be refunded to the buyer immediately.
/// @param values Amount of ether to exchange for each resource, in wei,
/// in canonical order.
/// @param to Recipient of tokens.
/// @return The number of each token purchased.
function buy(uint256[NUM_RESOURCES] calldata values, address to)
external payable onlyInitialized
returns (uint256[NUM_RESOURCES] memory bought) {
_touch();
uint256 remaining = msg.value;
for (uint8 i = 0; i < NUM_RESOURCES; i++) {
uint256 size = values[i];
require(size <= remaining, ERROR_INSUFFICIENT);
remaining -= size;
Token storage token = _tokens[_tokenAddresses[i]];
bought[i] = calculatePurchaseReturn(
token.supply, token.funds, CONNECTOR_WEIGHT, size);
if (bought[i] > 0) {
_mint(token, to, bought[i]);
token.funds = token.funds.add(size);
emit Bought(token.token, to, size, bought[i]);
}
}
// Refund any overpayment.
if (remaining > 0)
msg.sender.transfer(remaining);
return bought;
}
/// @dev Sell tokens for ether.
/// @param amounts Amount of ether to exchange for each resource, in wei,
/// in canonical order.
/// @param to Recipient of ether.
/// @return The combined amount of ether received.
function sell(uint256[NUM_RESOURCES] calldata amounts, address payable to)
external onlyInitialized returns (uint256 value) {
_touch();
value = 0;
for (uint8 i = 0; i < NUM_RESOURCES; i++) {
uint256 size = amounts[i];
Token storage token = _tokens[_tokenAddresses[i]];
uint256 _value = calculateSaleReturn(
token.supply, token.funds, CONNECTOR_WEIGHT, size);
if (_value > 0) {
_burn(token, msg.sender, size);
token.funds = token.funds.sub(_value);
value = value.add(_value);
emit Sold(token.token, to, size, _value);
}
}
if (value > 0)
to.transfer(value);
return value;
}
/// @dev Stash tokens belonging to `from`.
/// These tokens will be held in a pool that will initially fill mint
/// operations until the pool is depleted.
/// Only an authority may call this.
/// @param from The owner whose tokens will be locked.
/// @param amounts The number of each token to locked, in canonical order.
function stash(address from, uint256[NUM_RESOURCES] calldata amounts)
external onlyInitialized onlyAuthority {
for (uint8 i = 0; i < NUM_RESOURCES; i++) {
Token storage token = _tokens[_tokenAddresses[i]];
uint256 bal = token.balances[from];
require(bal >= amounts[i], ERROR_INSUFFICIENT);
token.balances[from] = token.balances[from].sub(amounts[i]);
token.stash = token.stash.add(amounts[i]);
}
}
/// @dev Mint tokens to `to`.
/// Only an authority may call this.
/// @param to The owner of the minted tokens.
/// @param amounts The number of each token to mint.
function mint(address to, uint256[NUM_RESOURCES] calldata amounts)
external onlyInitialized onlyAuthority {
_touch();
// #for TOKEN, IDX in map(range(NUM_RESOURCES), R => `_tokens[_tokenAddresses[${R}]]`)
_mint($$(TOKEN), to, amounts[$$(IDX)]);
// #done
}
/// @dev Burn tokens owned by `from`.
/// Will revert if insufficient supply or balance.
/// @param token The token state instance.
/// @param from The token owner.
/// @param amount The number of tokens to burn (in wei).
function _burn(Token storage token, address from, uint256 amount)
private {
uint256 balance = token.balances[from];
require(token.supply >= amount, ERROR_INSUFFICIENT);
require(balance >= amount, ERROR_INSUFFICIENT);
token.supply -= amount;
token.balances[from] -= amount;
}
/// @dev Mint tokens to be owned by `to`.
/// Stashed tokens will first be used to fill the operation, keeping the
/// supply the same, then any outstanding amount will cause new tokens to be
/// minted, increasing the supply.
/// @param token The token state instance.
/// @param to The token owner.
/// @param amount The number of tokens to burn (in wei).
function _mint(Token storage token, address to, uint256 amount)
private {
// Try to fill it with stashed tokens first.
if (token.stash >= amount)
token.stash -= amount;
else {
// Not enough in stash, mint the outstanding amount.
token.supply = token.supply.add(amount - token.stash);
token.stash = 0;
}
token.balances[to] = token.balances[to].add(amount);
}
/// @dev Move tokens between andresses.
/// Will revert if `from` has insufficient balance.
/// @param token The token state instance.
/// @param from The token owner.
/// @param to The token receiver.
/// @param amount The number of tokens to move (in wei).
function _transfer(
Token storage token, address from, address to, uint256 amount)
private {
assert(token.token != ZERO_ADDRESS);
require(to != address(this), ERROR_INVALID);
require(to != ZERO_ADDRESS, ERROR_INVALID);
require(token.balances[from] >= amount, ERROR_INSUFFICIENT);
assert(token.supply + amount >= amount);
token.balances[from] -= amount;
token.balances[to] = token.balances[to].add(amount);
}
/// @dev Calculate the price of a token.
/// @param funds The funds (ether) held by the market.
/// @param supply The token's supply.
/// @return The (ether) price.
function _getTokenPrice(uint256 funds, uint256 supply)
private pure returns (uint256) {
return ((1 ether) * funds) / ((supply * CONNECTOR_WEIGHT) / PPM_ONE);
}
/// @dev Update the price yesterday for all tokens.
/// Nothing will happen if less than a day has passed since the last
/// update.
function _touch() private {
uint64 _now = $(BLOCKTIME);
if (_now > yesterday && _now - yesterday >= $$(ONE_DAY)) {
// #for TOKEN in map(range(NUM_RESOURCES), (X) => `_tokens[_tokenAddresses[${X}]]`)
$$(TOKEN).priceYesterday = _getTokenPrice(
$$(TOKEN).funds,
$$(TOKEN).supply);
// #done
yesterday = _now;
}
}
// #if TEST
// solhint-disable
// The current blocktime.
uint64 public _blockTime = uint64(block.timestamp);
// Set the current blocktime.
function __setBlockTime(uint64 t) public {
_blockTime = t;
}
// Advance the current blocktime.
function __advanceTime(uint64 dt) public {
_blockTime += dt;
}
// #endif
}
| Fund the markets. Attached ether will be distributed evenly across all token markets. | function() external payable onlyInitialized {
if (msg.value > 0) {
_touch();
for (uint8 i = 0; i < NUM_RESOURCES; i++) {
Token storage token = _tokens[_tokenAddresses[i]];
token.funds = token.funds.add(msg.value/NUM_RESOURCES);
}
emit Funded(msg.value);
}
}
| 5,542,695 |
./partial_match/1/0x4D25148347047f7554c1902dd11d5cCFA85311b5/sources/SHILLER.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), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
| 2,774,044 |
./partial_match/10/0x52782699900DF91B58eCD618e77847C5774dCD2e/sources/OptimisticBunnies.sol | ERC-721 Non-Fungible Token Standard, optional enumeration extension/ | interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity >=0.7.0 <0.9.0;
}
| 3,531,904 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
import "../interfaces/IStakeRegistry.sol";
import "../libraries/LibTokenStake1.sol";
import "../common/AccessibleCommon.sol";
/// @title Stake Registry
/// @notice Manage the vault list by phase. Manage the list of staking contracts in the vault.
contract StakeRegistry is AccessibleCommon, IStakeRegistry {
bytes32 public constant ZERO_HASH =
0x0000000000000000000000000000000000000000000000000000000000000000;
/// @dev TOS address
address public tos;
/// @dev TON address in Tokamak
address public ton;
/// @dev WTON address in Tokamak
address public wton;
/// @dev Depositmanager address in Tokamak
address public depositManager;
/// @dev SeigManager address in Tokamak
address public seigManager;
/// @dev swapProxy address in Tokamak
address public swapProxy;
/// Contracts included in the phase
mapping(uint256 => address[]) public phases;
/// Vault address mapping with vault name hash
mapping(bytes32 => address) public vaults;
/// Vault name hash mapping with vault address
mapping(address => bytes32) public vaultNames;
/// List of staking contracts included in the vault
mapping(address => address[]) public stakeContractsOfVault;
/// Vault address of staking contract
mapping(address => address) public stakeContractVault;
/// Defi Info
mapping(bytes32 => LibTokenStake1.DefiInfo) public override defiInfo;
modifier nonZero(address _addr) {
require(_addr != address(0), "StakeRegistry: zero address");
_;
}
/// @dev event on add the vault
/// @param vault the vault address
/// @param phase the phase of TOS platform
event AddedVault(address indexed vault, uint256 phase);
/// @dev event on add the stake contract in vault
/// @param vault the vault address
/// @param stakeContract the stake contract address created
event AddedStakeContract(
address indexed vault,
address indexed stakeContract
);
/// @dev event on set the addresses related to tokamak
/// @param ton the TON address
/// @param wton the WTON address
/// @param depositManager the DepositManager address
/// @param seigManager the SeigManager address
/// @param swapProxy the SwapProxy address
event SetTokamak(
address ton,
address wton,
address depositManager,
address seigManager,
address swapProxy
);
/// @dev event on add the information related to defi.
/// @param nameHash the name hash
/// @param name the name of defi identify
/// @param router the entry address
/// @param ex1 the extra 1 addres
/// @param ex2 the extra 2 addres
/// @param fee fee
/// @param routerV2 the uniswap2 router address
event AddedDefiInfo(
bytes32 nameHash,
string name,
address router,
address ex1,
address ex2,
uint256 fee,
address routerV2
);
/// @dev constructor of StakeRegistry
/// @param _tos TOS address
constructor(address _tos) {
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(ADMIN_ROLE, msg.sender);
tos = _tos;
}
/// @dev Set addresses for Tokamak integration
/// @param _ton TON address
/// @param _wton WTON address
/// @param _depositManager DepositManager address
/// @param _seigManager SeigManager address
function setTokamak(
address _ton,
address _wton,
address _depositManager,
address _seigManager,
address _swapProxy
)
external
override
onlyOwner
nonZero(_ton)
nonZero(_wton)
nonZero(_depositManager)
nonZero(_seigManager)
nonZero(_swapProxy)
{
ton = _ton;
wton = _wton;
depositManager = _depositManager;
seigManager = _seigManager;
swapProxy = _swapProxy;
emit SetTokamak(ton, wton, depositManager, seigManager, swapProxy);
}
/// @dev Add information related to Defi
/// @param _name name . ex) UNISWAP_V3
/// @param _router entry point of defi
/// @param _ex1 additional variable . ex) positionManagerAddress in Uniswap V3
/// @param _ex2 additional variable . ex) WETH Address in Uniswap V3
/// @param _fee fee
/// @param _routerV2 In case of uniswap, router address of uniswapV2
function addDefiInfo(
string calldata _name,
address _router,
address _ex1,
address _ex2,
uint256 _fee,
address _routerV2
) external override onlyOwner nonZero(_router) {
bytes32 nameHash = keccak256(abi.encodePacked(_name));
require(nameHash != ZERO_HASH, "StakeRegistry: nameHash zero");
LibTokenStake1.DefiInfo storage _defiInfo = defiInfo[nameHash];
_defiInfo.name = _name;
_defiInfo.router = _router;
_defiInfo.ext1 = _ex1;
_defiInfo.ext2 = _ex2;
_defiInfo.fee = _fee;
_defiInfo.routerV2 = _routerV2;
emit AddedDefiInfo(
nameHash,
_name,
_router,
_ex1,
_ex2,
_fee,
_routerV2
);
}
/// @dev Add Vault
/// @dev It is excuted by proxy
/// @param _vault vault address
/// @param _phase phase ex) 1,2,3
/// @param _vaultName hash of vault's name
function addVault(
address _vault,
uint256 _phase,
bytes32 _vaultName
) external override onlyOwner {
require(
vaultNames[_vault] == ZERO_HASH || vaults[_vaultName] == address(0),
"StakeRegistry: addVault input value is not zero"
);
vaults[_vaultName] = _vault;
vaultNames[_vault] = _vaultName;
phases[_phase].push(_vault);
emit AddedVault(_vault, _phase);
}
/// @dev Add StakeContract in vault
/// @dev It is excuted by proxy
/// @param _vault vault address
/// @param _stakeContract StakeContract address
function addStakeContract(address _vault, address _stakeContract)
external
override
onlyOwner
{
require(
vaultNames[_vault] != ZERO_HASH &&
stakeContractVault[_stakeContract] == address(0),
"StakeRegistry: input is zero"
);
stakeContractVault[_stakeContract] = _vault;
stakeContractsOfVault[_vault].push(_stakeContract);
emit AddedStakeContract(_vault, _stakeContract);
}
/// @dev Get addresses for Tokamak interface
/// @return (ton, wton, depositManager, seigManager)
function getTokamak()
external
view
override
returns (
address,
address,
address,
address,
address
)
{
return (ton, wton, depositManager, seigManager, swapProxy);
}
/// @dev Get indos for UNISWAP_V3 interface
/// @return (uniswapRouter, npm, wethAddress, fee)
function getUniswap()
external
view
override
returns (
address,
address,
address,
uint256,
address
)
{
bytes32 nameHash = keccak256(abi.encodePacked("UNISWAP_V3"));
return (
defiInfo[nameHash].router,
defiInfo[nameHash].ext1,
defiInfo[nameHash].ext2,
defiInfo[nameHash].fee,
defiInfo[nameHash].routerV2
);
}
/// @dev Get addresses of vaults of index phase
/// @param _index the phase number
/// @return the list of vaults of phase[_index]
function phasesAll(uint256 _index)
external
view
override
returns (address[] memory)
{
return phases[_index];
}
/// @dev Get addresses of staker of _vault
/// @param _vault the vault's address
/// @return the list of stakeContracts of vault
function stakeContractsOfVaultAll(address _vault)
external
view
override
returns (address[] memory)
{
return stakeContractsOfVault[_vault];
}
/// @dev Checks if a vault is withing the given phase
/// @param _phase the phase number
/// @param _vault the vault's address
/// @return valid true or false
function validVault(uint256 _phase, address _vault)
external
view
override
returns (bool valid)
{
require(phases[_phase].length > 0, "StakeRegistry: validVault is fail");
for (uint256 i = 0; i < phases[_phase].length; i++) {
if (_vault == phases[_phase][i]) {
return true;
}
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
interface IStakeRegistry {
/// @dev Set addresses for Tokamak integration
/// @param _ton TON address
/// @param _wton WTON address
/// @param _depositManager DepositManager address
/// @param _seigManager SeigManager address
/// @param _swapProxy Proxy address that can swap TON and WTON
function setTokamak(
address _ton,
address _wton,
address _depositManager,
address _seigManager,
address _swapProxy
) external;
/// @dev Add information related to Defi
/// @param _name name . ex) UNISWAP_V3
/// @param _router entry point of defi
/// @param _ex1 additional variable . ex) positionManagerAddress in Uniswap V3
/// @param _ex2 additional variable . ex) WETH Address in Uniswap V3
/// @param _fee fee
/// @param _routerV2 In case of uniswap, router address of uniswapV2
function addDefiInfo(
string calldata _name,
address _router,
address _ex1,
address _ex2,
uint256 _fee,
address _routerV2
) external;
/// @dev Add Vault
/// @dev It is excuted by proxy
/// @param _vault vault address
/// @param _phase phase ex) 1,2,3
/// @param _vaultName hash of vault's name
function addVault(
address _vault,
uint256 _phase,
bytes32 _vaultName
) external;
/// @dev Add StakeContract in vault
/// @dev It is excuted by proxy
/// @param _vault vault address
/// @param _stakeContract StakeContract address
function addStakeContract(address _vault, address _stakeContract) external;
/// @dev Get addresses for Tokamak interface
/// @return (ton, wton, depositManager, seigManager)
function getTokamak()
external
view
returns (
address,
address,
address,
address,
address
);
/// @dev Get indos for UNISWAP_V3 interface
/// @return (uniswapRouter, npm, wethAddress, fee)
function getUniswap()
external
view
returns (
address,
address,
address,
uint256,
address
);
/// @dev Checks if a vault is withing the given phase
/// @param _phase the phase number
/// @param _vault the vault's address
/// @return valid true or false
function validVault(uint256 _phase, address _vault)
external
view
returns (bool valid);
function phasesAll(uint256 _index) external view returns (address[] memory);
function stakeContractsOfVaultAll(address _vault)
external
view
returns (address[] memory);
/// @dev view defi info
/// @param _name hash name : keccak256(abi.encodePacked(_name));
/// @return name _name ex) UNISWAP_V3, UNISWAP_V3_token0_token1
/// @return router entry point of defi
/// @return ext1 additional variable . ex) positionManagerAddress in Uniswap V3
/// @return ext2 additional variable . ex) WETH Address in Uniswap V3
/// @return fee fee
/// @return routerV2 In case of uniswap, router address of uniswapV2
function defiInfo(bytes32 _name)
external
returns (
string calldata name,
address router,
address ext1,
address ext2,
uint256 fee,
address routerV2
);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
library LibTokenStake1 {
enum DefiStatus {
NONE,
APPROVE,
DEPOSITED,
REQUESTWITHDRAW,
REQUESTWITHDRAWALL,
WITHDRAW,
END
}
struct DefiInfo {
string name;
address router;
address ext1;
address ext2;
uint256 fee;
address routerV2;
}
struct StakeInfo {
string name;
uint256 startBlock;
uint256 endBlock;
uint256 balance;
uint256 totalRewardAmount;
uint256 claimRewardAmount;
}
struct StakedAmount {
uint256 amount;
uint256 claimedBlock;
uint256 claimedAmount;
uint256 releasedBlock;
uint256 releasedAmount;
uint256 releasedTOSAmount;
bool released;
}
struct StakedAmountForSTOS {
uint256 amount;
uint256 startBlock;
uint256 periodBlock;
uint256 rewardPerBlock;
uint256 claimedBlock;
uint256 claimedAmount;
uint256 releasedBlock;
uint256 releasedAmount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AccessRoleCommon.sol";
contract AccessibleCommon is AccessRoleCommon, AccessControl {
modifier onlyOwner() {
require(isAdmin(msg.sender), "Accessible: Caller is not an admin");
_;
}
/// @dev add admin
/// @param account address to add
function addAdmin(address account) public virtual onlyOwner {
grantRole(ADMIN_ROLE, account);
}
/// @dev remove admin
/// @param account address to remove
function removeAdmin(address account) public virtual onlyOwner {
renounceRole(ADMIN_ROLE, account);
}
/// @dev transfer admin
/// @param newAdmin new admin address
function transferAdmin(address newAdmin) external virtual onlyOwner {
require(newAdmin != address(0), "Accessible: zero address");
require(msg.sender != newAdmin, "Accessible: same admin");
grantRole(ADMIN_ROLE, newAdmin);
renounceRole(ADMIN_ROLE, msg.sender);
}
/// @dev whether admin
/// @param account address to check
function isAdmin(address account) public view virtual returns (bool) {
return hasRole(ADMIN_ROLE, account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.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, 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 {
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 `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 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.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract AccessRoleCommon {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant BURNER_ROLE = keccak256("BURNER");
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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;
}
}
| Get indos for UNISWAP_V3 interface return (uniswapRouter, npm, wethAddress, fee) | function getUniswap()
external
view
override
returns (
address,
address,
address,
uint256,
address
)
{
bytes32 nameHash = keccak256(abi.encodePacked("UNISWAP_V3"));
return (
defiInfo[nameHash].router,
defiInfo[nameHash].ext1,
defiInfo[nameHash].ext2,
defiInfo[nameHash].fee,
defiInfo[nameHash].routerV2
);
}
| 9,862,526 |
pragma solidity ^0.4.0;
contract dkgEnc {
/**
* DKG phases:
*
* 0) Create the contract with a threshold (t) and
* number of participants.
*
* 1) Each of the participants sends a deposit and
* a public key address that he owns.
*
* (not on contract) - each participant generates t+1
* random sampled coefficients from the (mod p) field.
*
* 2) Each of the participants sends its public commitments
* (the generator exponentiated t+1 coefficients) and
* encrypted private commitments for all of the other
* particpants.
*
* 3) Complaint - each participant can send a complaint tx
* about one of the followings:
* a) 2 distinct participants offered the same public commitment
(one is enough). (TODO)
* b) Some participant offered invalid commitment (invalid is:
* duplicated, insufficient, unmatching commitments G1 to G2)
* c) Umatched private and public commitments.
* d) Time out.
*
*/
/**
* Important note: at this point this contract purpose is as a
* POC only, therefore its security is unreliable.
*/
struct Participant {
address ethPk; // Ethereum pk
uint256[2] encPk; // pk for encryption
mapping(uint16 => uint256[2]) publicCommitmentsG1; // coefficient index to commitment
mapping(uint16 => uint256[4]) publicCommitmentsG2;
// TODO: should be encrypted (and possibly off chain).
mapping(uint16 => uint256) encPrivateCommitments; // node's index to its commitment
bool isCommitted;
}
enum Phase {Enrollment, Commit, PostCommit, EndSuccess, EndFail} // start from 0
event PhaseChange(
Phase phase
);
event NewCommit(
uint16 committerIndex,
uint256[] pubCommitG1,
uint256[] pubCommitG2,
uint256[] prvCommit
);
event ParticipantJoined(
uint16 index
);
Phase public curPhase;
// The curve y^2 = x^3 + a*x + b (x,y in modulo n field)
uint256 public constant p = 0x30644E72E131A029B85045B68181585D97816A916871CA8D3C208C16D87CFD47;
uint256 public constant q = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001;
//uint256 public constant a = 0;
//uint256 public constant b = 3;
// G1 generator (on the curve)
uint256[2] public g1 = [
0x0000000000000000000000000000000000000000000000000000000000000001,
0x0000000000000000000000000000000000000000000000000000000000000002
];
// G2 generator (on the curve)
uint256[4] public g2 = [
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed,
0x90689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
];
uint256 public depositWei;
uint16 public t; // threshold
uint16 public n; // numer of participants;
uint16 public curN; // current num of participants
uint256 public phaseStart;
uint256 public constant commitTimeout = 100;
// mapping from node's index to a participant
mapping(uint16 => Participant) public participants;
constructor(uint16 threshold, uint16 numParticipants, uint deposit) public
{
t = threshold;
n = numParticipants;
depositWei = deposit;
curPhase = Phase.Enrollment;
if (n <= t || t == 0) {
revert("wrong input");
}
phaseStart = block.number;
}
modifier checkDeposit() {
if (msg.value != depositWei) revert("wrong deposit");
_;
}
modifier checkAuthorizedSender(uint16 index) {
if (participants[index].ethPk != msg.sender) revert("not authorized sender");
_;
}
modifier beFalse(bool term) {
if (term) revert();
_;
}
modifier inPhase(Phase phase) {
if (curPhase != phase) revert("wrong phase");
_;
}
modifier notInPhase(Phase phase) {
if (curPhase == phase) revert("wrong phase");
_;
}
// Join the DKG (enrollment - phase 1).
// A point on G1 that represents this participant's pk for encryption have
// to be published. The publisher have to know the secret that generates
// this point.
function join(uint256[2] encPk)
checkDeposit()
inPhase(Phase.Enrollment)
external payable
returns (uint16 index)
{
// TODO: phase timeout, check pk
uint16 cn = curN;
address sender = msg.sender;
// Check the pk isn't registered already
for (uint16 i = 1; i <= cn; i++) {
if (participants[i].ethPk == sender) {
revert("already joined");
}
}
cn++;
participants[cn] = Participant({ethPk : sender, encPk : encPk, isCommitted : false});
curN = cn;
// Abort if capacity on participants was reached
if (cn == n) {
curPhase = Phase.Commit;
emit PhaseChange(Phase.Commit);
}
emit ParticipantJoined(cn);
return cn;
}
// Send commitments (phase 2).
//
// pubCommitG1 is composed of t+1 commitments to local randomly sampled
// coefficients. Each commitment should be on the G1 curve (affine
// coordinates) and therefore it has 2 coordinates. Thus, the input array
// is of size (2t+2) and the i'th commitment will be in indices (2i) and
// (2i+1).
//
// pubCommitG2 is composed of t+1 commitments to same sampled coefficients
// from pubCommitG1. Each commitment should be on the G2 curve (affine
// coordinates) and therefore it has 4 coordinates. Thus, the input array
// is of size (4t+4) and the i'th commitment will be in indices (4i),(4i+1),
// (4i+2),(4i+3).
//
// prCommit is an array of size n, where the first index matches the
// first participant (participant index 1) and so forth. The commitment
// is a calculation on the localy generated polynomial in the particpant's
// index. This calculation is encrypted by the recevier pk for encryption.
// The senderIndex private commitment is ignored and can be anything
// (but can't be skipped).
//
// Note that this function does not verifies the committed data, it
// should be done outside of this contract scope. In case of an
// invalid committed data use complaints.
function commit(uint16 senderIndex, uint256[] pubCommitG1,
uint256[] pubCommitG2, uint256[] encPrCommit)
inPhase(Phase.Commit)
checkAuthorizedSender(senderIndex)
beFalse(participants[senderIndex].isCommitted)
external
returns (bool)
{
// TODO: phase timeout, make prCommit encrypted, verify sender
// index matches the sender's address.
assignCommitments(senderIndex, pubCommitG1, pubCommitG2, encPrCommit);
uint16 committedNum = curN - 1;
curN = committedNum;
if (committedNum == 0) {
curPhase = Phase.PostCommit;
phaseStart = block.number;
emit PhaseChange(Phase.PostCommit);
}
}
// Assigns the commitments to the sender with index of senderIndex.
function assignCommitments(uint16 senderIndex, uint256[] pubCommitG1,
uint256[] pubCommitG2, uint256[] prCommit)
internal
{
// TODO: consider merging the following loops to save gas
uint16 nParticipants = n;
uint16 threshold = t;
// Verify input size
if (pubCommitG1.length != (threshold * 2 + 2)
|| pubCommitG2.length != (threshold * 4 + 4)
|| prCommit.length != nParticipants) {
revert("input size invalid");
}
// Assign public commitments from G1 and G2
for (uint16 i = 0; i < (threshold + 1); i++) {
participants[senderIndex].publicCommitmentsG1[i] = [pubCommitG1[2 * i], pubCommitG1[2 * i + 1]];
participants[senderIndex].publicCommitmentsG2[i] = [
pubCommitG2[4 * i], pubCommitG2[4 * i + 1], pubCommitG2[4 * i + 2], pubCommitG2[4 * i + 3]
];
}
// Assign private commitments
for (i = 1; i <= nParticipants; i++) {
if (senderIndex != i) {
participants[senderIndex].encPrivateCommitments[i] = prCommit[i - 1];
}
}
participants[senderIndex].isCommitted = true;
emit NewCommit(senderIndex, pubCommitG1, pubCommitG2, prCommit);
}
// Call this when in Phase.PostCommit for more than commitTimeout
// blocks and no comlaint has to be made.
function phaseChange()
inPhase(Phase.PostCommit)
external
{
uint curBlockNum = block.number;
if (curBlockNum > (phaseStart + commitTimeout)) {
curPhase = Phase.EndSuccess;
emit PhaseChange(Phase.EndSuccess);
// TODO: return money to all
slash(0);
}
else {
revert();
}
}
// Returns the group PK.
// This can only be performed after the DKG has ended. This
// means only when the current phase is Phase.End .
function getGroupPK()
inPhase(Phase.EndSuccess)
public returns (uint256[2] groupPK)
{
uint16 nParticipants = n;
groupPK = participants[1].publicCommitmentsG1[0];
for (uint16 i = 2; i <= nParticipants; i++) {
groupPK = ecadd(groupPK, participants[i].publicCommitmentsG1[0]);
}
}
////////////////
// Complaints //
////////////////
// A complaint on some public commit. If for some reason this
// function fails it will slash the complainer deposit! (unless some
// unauthorized address made the transaction or the wrong phase).
//
// The complaint should be called when the public commitments coming
// from the G1 group does not match to the ones from G2 group (using pairing).
function complaintPublicCommit(uint16 complainerIndex, uint16 accusedIndex,
uint16 pubCommitIndex)
checkAuthorizedSender(complainerIndex)
notInPhase(Phase.EndFail)
notInPhase(Phase.EndSuccess)
public
{
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
Participant storage accused = participants[accusedIndex];
if (!accused.isCommitted) {
slash(complainerIndex);
return;
}
if (pairingCheck(accused.publicCommitmentsG1[pubCommitIndex],
g2, g1, accused.publicCommitmentsG2[pubCommitIndex])) {
slash(complainerIndex);
}
else {
slash(accusedIndex);
}
}
// A complaint on some private commitment. If for some reason this
// function fails it will slash the complainer deposit! (unless some
// unauthorized address made the transaction or the wrong phase).
//
// The complaint should be called when some private commitment does
// not match to the public commitment.
// The complainer has to publish the secret key from which its pk
// for encryption is derived.
function complaintPrivateCommit(uint16 complainerIndex,
uint16 accusedIndex,
uint256 complainerSk)
checkAuthorizedSender(complainerIndex)
notInPhase(Phase.EndFail)
notInPhase(Phase.EndSuccess)
public
{
// TODO: a secret key should be inputted so the encrypted private
// commitment would reveal, also a check for edge cases has to be
// done (e.g., when no one has yet committed)
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
Participant storage accused = participants[accusedIndex];
if (!accused.isCommitted) {
slash(complainerIndex);
return;
}
uint256 encPrvCommit = accused.encPrivateCommitments[complainerIndex];
if (!isEqualPoints(participants[complainerIndex].encPk, ecmul(g1, complainerSk))) {
slash(complainerIndex);
return;
}
uint256 prvCommit = uint256(decrypt(accused.encPk, complainerSk, bytes32(encPrvCommit)));
uint256[2] memory temp;
uint256[2] memory RHS;
uint256[2] memory LHS = ecmul(g1, prvCommit);
for (uint16 i = 0; i < t + 1; i++) {
temp = (ecmul(accused.publicCommitmentsG1[i], complainerIndex ** i));
if (i == 0) {
RHS = temp;
}
else {
RHS = ecadd(RHS, temp);
}
}
if (isEqualPoints(LHS, RHS)) {
slash(complainerIndex);
}
else {
slash(accusedIndex);
}
}
// Divides the deposited balance in the contract between
// the enrolled paricipants except for the participant
// with the slashedIndex. Send slashedIndex = 0 in order
// to divide it between all the participants (no slashing).
function slash(uint16 slashedIndex) private {
uint16 nParticipants = n;
uint256 amount;
if (slashedIndex == 0) {
amount = address(this).balance / nParticipants;
}
else {
amount = address(this).balance / (nParticipants - 1);
}
for (uint16 i = 1; i < (nParticipants + 1); i++) {
if (i != slashedIndex) {
if (!participants[i].ethPk.send(amount)) {
revert();
}
}
}
}
function decrypt(uint256[2] encrypterPk, uint256 decrypterSk, bytes32 encData)
internal view
returns (bytes32 decryptedData)
{
bytes32 secret = keccak256(abi.encodePacked(ecmul(encrypterPk, decrypterSk)));
return encData ^ secret;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// EC operations - precompiled contracts for bn256 only!
////////////////////////////////////////////////////////
function ecmul(uint256[2] p0, uint256 scalar) public view
returns (uint256[2] p1)
{
uint256[3] memory input;
input[0] = p0[0];
input[1] = p0[1];
input[2] = scalar;
assembly{
// call ecmul precompile
if iszero(call(not(0), 0x07, 0, input, 0x60, p1, 0x40)) {
revert(0, 0)
}
}
}
function ecadd(uint256[2] p0,
uint256[2] p1) public view
returns (uint256[2] p2)
{
uint256[4] memory input;
input[0] = p0[0];
input[1] = p0[1];
input[2] = p1[0];
input[3] = p1[1];
assembly{
// call ecadd precompile
if iszero(call(not(0), 0x06, 0, input, 0x80, p2, 0x40)) {
revert(0, 0)
}
}
}
function pairingCheck(uint256[2] a, uint256[4] x, uint256[2] b, uint256[4] y)
internal
returns (bool)
{
//returns e(a,x) == e(b,y)
uint256[12] memory input = [
a[0], a[1], x[0], x[1], x[2], x[3],
b[0], p - b[1], y[0], y[1], y[2], y[3]
];
uint[1] memory result;
assembly {
if iszero(call(not(0), 0x08, 0, input, 0x180, result, 0x20)) {
revert(0, 0)
}
}
return result[0] == 1;
}
// Return true iff p1 equals to p2 (points on the elliptic curve)
function isEqualPoints(uint256[2] p1, uint256[2] p2) public pure
returns (bool isEqual)
{
return (p1[0] == p2[0] && p1[1] == p2[1]);
}
function getParticipantPkEnc(uint16 participantIndex)
view
external
returns (uint256[2] encPk)
{
return participants[participantIndex].encPk;
}
function getParticipantPubCommitG1(uint16 participantIndex, uint16 coefIndex)
view
external
returns (uint256[2] publicCommitmentsG1)
{
return participants[participantIndex].publicCommitmentsG1[coefIndex];
}
function getParticipantPubCommitG2(uint16 participantIndex, uint16 coefIndex)
view
external
returns (uint256[4] publicCommitmentsG2)
{
return participants[participantIndex].publicCommitmentsG2[coefIndex];
}
function getParticipantPrvCommit(uint16 participantIndex, uint16 committedToIndex)
view
external
returns (uint256 encPrivateCommitments)
{
return participants[participantIndex].encPrivateCommitments[committedToIndex];
}
function getParticipantIsCommitted(uint16 participantIndex)
view
external
returns (bool isCommitted)
{
return participants[participantIndex].isCommitted;
}
}
/**
Test parameters:
n=2
t=1
coefficients:
a0) 54379457673493
a1) 23950433293405
b0) 453845345602931234235
b1) 976507650679506234134
public commitments:
a0)
1368041971066725411361239018179403078339688804905262551154469895335979601856
1618821492510491564023544834479645350362276877645830361512548330678288690656
a1)
2631817276443378672842587294280308402376367224288772184477397977654447923479
10839063031804877909681801875549944362615153185887194276974645822919437293936
b0)
13557179362105442634413454166511695479402464592547795407903173557675549038583
14036788543633373773860064791695546493243519155298095713201690292908488603901
b1)
1410561832783565967033505993299263011778160659525151177822679323808323926727
13048336431799703732972170157397576895462246813007390422018149570212241640252
sks for decryption:
a)9163450 (0x8bd2ba)
b)197435619 (0xbc4a0e3)
corresponding pks:
a)
8010568142108063162131985722241290538226183630284938005062991216917635380726
19057704389966790842586953303181803223520621589676400762135428513026389437262
b)
20560911457302142627844632840089789900964525435158247870992611991075785849245
6050521612570208504883690818928114121824160212045800551636642965355310285042
private commitments:
fa(2)
102280324260303
fb(1)
1430352996282437468369
private commitmente encrypted:
fa(2)
0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf314443cb5d4dece465
fb(1)
0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf7cce6131901dd9c57b
Group PK:
5837875810486042432133468170632608166601746087751836698563291230806091472694,
20890074343725101418521449931290202203738610819454311822513791170653396069990
## Join
["0x11b5d2263b698dd637fb356ea748350b072265cf1acfaf374201f8e99c5bb5f6","0x2a2247476997f4e72285cc8adc57bb0350a105d8f109e523836fc7611d8deb4e"]
["0x2d75104069619e845ea0f055105e3adb22f07fe1206c093880b9fee9942cb99d","0xd60794fcd581fed59e19e802dcc263a5d53f6a04ddebba96a77745474f700f2"]
## Commit
1,
["0x30648c8ef4e8e38d2db668db8a4cab5513343aad935530559090e8a51354fc0",
"0x39438725e6ce47a9b49d4a0b2d90e1cee07d3d7e9a44adb9c0a3cf84078ade0",
"0x5d18e484aeddc886ba162e2fa4bf8bcc125d32230a3fbea6e39ef74de3d6117",
"0x17f6b138a7105622c493ac45d228e9c858544c47227f27a548942c2f01d59970"],
[1,2,3,4,5,6,7,8],
["0x0000000000000000000000000000000000000000000000000000000000000000",
"0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf314443cb5d4dece465"]
2,
["0x1df91772c249f1b2a7e539242ed9eb60e1475f159a376614e91de79c644097f7",
"0x1f088a7004f9c9035af5f4686a5494f576415da8de528c40a67702c5399338fd",
"0x31e598642c78a683eedf66cf7cd4a35a3dd5b5fd8ea947a1c53ab867154fac7",
"0x1cd918c17d9ea92a1a3efb8a999d577d06058a1b205e99769bdc06b6686c8b3c"],
[1,2,3,4,5,6,7,8],
["0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf7cce6131901dd9c57b",
"0x0000000000000000000000000000000000000000000000000000000000000000"]
*/ | Return true iff p1 equals to p2 (points on the elliptic curve) | function isEqualPoints(uint256[2] p1, uint256[2] p2) public pure
returns (bool isEqual)
{
return (p1[0] == p2[0] && p1[1] == p2[1]);
}
| 913,421 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.2;
import { IMACI } from "./IMACI.sol";
import { Params } from "./Params.sol";
import { Hasher } from "./crypto/Hasher.sol";
import { Verifier } from "./crypto/Verifier.sol";
import { SnarkCommon } from "./crypto/SnarkCommon.sol";
import { SnarkConstants } from "./crypto/SnarkConstants.sol";
import { DomainObjs, IPubKey, IMessage } from "./DomainObjs.sol";
import { AccQueue, AccQueueQuinaryMaci } from "./trees/AccQueue.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { VkRegistry } from "./VkRegistry.sol";
import { EmptyBallotRoots } from "./trees/EmptyBallotRoots.sol";
contract MessageAqFactory is Ownable {
function deploy(uint256 _subDepth)
public
onlyOwner
returns (AccQueue) {
AccQueue aq = new AccQueueQuinaryMaci(_subDepth);
aq.transferOwnership(owner());
return aq;
}
}
contract PollDeploymentParams {
struct ExtContracts {
VkRegistry vkRegistry;
IMACI maci;
AccQueue messageAq;
}
}
/*
* A factory contract which deploys Poll contracts. It allows the MACI contract
* size to stay within the limit set by EIP-170.
*/
contract PollFactory is Params, IPubKey, IMessage, Ownable, Hasher, PollDeploymentParams {
MessageAqFactory public messageAqFactory;
function setMessageAqFactory(MessageAqFactory _messageAqFactory)
public
onlyOwner {
messageAqFactory = _messageAqFactory;
}
/*
* Deploy a new Poll contract and AccQueue contract for messages.
*/
function deploy(
uint256 _duration,
MaxValues memory _maxValues,
TreeDepths memory _treeDepths,
BatchSizes memory _batchSizes,
PubKey memory _coordinatorPubKey,
VkRegistry _vkRegistry,
IMACI _maci,
address _pollOwner
) public onlyOwner returns (Poll) {
uint256 treeArity = 5;
// Validate _maxValues
// NOTE: these checks may not be necessary. Removing them will save
// 0.28 Kb of bytecode.
// maxVoteOptions must be less than 2 ** 50 due to circuit limitations;
// it will be packed as a 50-bit value along with other values as one
// of the inputs (aka packedVal)
require(
_maxValues.maxMessages <= treeArity ** uint256(_treeDepths.messageTreeDepth) &&
_maxValues.maxMessages >= _batchSizes.messageBatchSize &&
_maxValues.maxMessages % _batchSizes.messageBatchSize == 0 &&
_maxValues.maxVoteOptions <= treeArity ** uint256(_treeDepths.voteOptionTreeDepth) &&
_maxValues.maxVoteOptions < (2 ** 50),
"PollFactory: invalid _maxValues"
);
AccQueue messageAq =
messageAqFactory.deploy(_treeDepths.messageTreeSubDepth);
ExtContracts memory extContracts;
// TODO: remove _vkRegistry; only PollProcessorAndTallyer needs it
extContracts.vkRegistry = _vkRegistry;
extContracts.maci = _maci;
extContracts.messageAq = messageAq;
Poll poll = new Poll(
_duration,
_maxValues,
_treeDepths,
_batchSizes,
_coordinatorPubKey,
extContracts
);
// Make the Poll contract own the messageAq contract, so only it can
// run enqueue/merge
messageAq.transferOwnership(address(poll));
// TODO: should this be _maci.owner() instead?
poll.transferOwnership(_pollOwner);
return poll;
}
}
/*
* Do not deploy this directly. Use PollFactory.deploy() which performs some
* checks on the Poll constructor arguments.
*/
contract Poll is
Params, Hasher, IMessage, IPubKey, SnarkCommon, Ownable,
PollDeploymentParams, EmptyBallotRoots {
// The coordinator's public key
PubKey public coordinatorPubKey;
uint256 public mergedStateRoot;
uint256 public coordinatorPubKeyHash;
// TODO: to reduce the Poll bytecode size, consider storing deployTime and
// duration in a mapping in the MACI contract
// The timestamp of the block at which the Poll was deployed
uint256 internal deployTime;
// The duration of the polling period, in seconds
uint256 internal duration;
function getDeployTimeAndDuration() public view returns (uint256, uint256) {
return (deployTime, duration);
}
// Whether the MACI contract's stateAq has been merged by this contract
bool public stateAqMerged;
// The commitment to the state leaves and the ballots. This is
// hash3(stateRoot, ballotRoot, salt).
// Its initial value should be
// hash(maciStateRootSnapshot, emptyBallotRoot, 0)
// Each successful invocation of processMessages() should use a different
// salt to update this value, so that an external observer cannot tell in
// the case that none of the messages are valid.
uint256 public currentSbCommitment;
uint256 internal numMessages;
function numSignUpsAndMessages() public view returns (uint256, uint256) {
uint numSignUps = extContracts.maci.numSignUps();
return (numSignUps, numMessages);
}
MaxValues public maxValues;
TreeDepths public treeDepths;
BatchSizes public batchSizes;
// Error codes. We store them as constants and keep them short to reduce
// this contract's bytecode size.
string constant ERROR_VK_NOT_SET = "PollE01";
string constant ERROR_SB_COMMITMENT_NOT_SET = "PollE02";
string constant ERROR_VOTING_PERIOD_PASSED = "PollE03";
string constant ERROR_VOTING_PERIOD_NOT_PASSED = "PollE04";
string constant ERROR_INVALID_PUBKEY = "PollE05";
string constant ERROR_MAX_MESSAGES_REACHED = "PollE06";
string constant ERROR_STATE_AQ_ALREADY_MERGED = "PollE07";
string constant ERROR_STATE_AQ_SUBTREES_NEED_MERGE = "PollE08";
uint8 private constant LEAVES_PER_NODE = 5;
event PublishMessage(Message _message, PubKey _encPubKey);
event MergeMaciStateAqSubRoots(uint256 _numSrQueueOps);
event MergeMaciStateAq(uint256 _stateRoot);
event MergeMessageAqSubRoots(uint256 _numSrQueueOps);
event MergeMessageAq(uint256 _messageRoot);
ExtContracts public extContracts;
/*
* Each MACI instance can have multiple Polls.
* When a Poll is deployed, its voting period starts immediately.
*/
constructor(
uint256 _duration,
MaxValues memory _maxValues,
TreeDepths memory _treeDepths,
BatchSizes memory _batchSizes,
PubKey memory _coordinatorPubKey,
ExtContracts memory _extContracts
) {
extContracts = _extContracts;
coordinatorPubKey = _coordinatorPubKey;
coordinatorPubKeyHash = hashLeftRight(_coordinatorPubKey.x, _coordinatorPubKey.y);
duration = _duration;
maxValues = _maxValues;
batchSizes = _batchSizes;
treeDepths = _treeDepths;
// Record the current timestamp
deployTime = block.timestamp;
}
/*
* A modifier that causes the function to revert if the voting period is
* not over.
*/
modifier isAfterVotingDeadline() {
uint256 secondsPassed = block.timestamp - deployTime;
require(
secondsPassed > duration,
ERROR_VOTING_PERIOD_NOT_PASSED
);
_;
}
function isAfterDeadline() public view returns (bool) {
uint256 secondsPassed = block.timestamp - deployTime;
return secondsPassed > duration;
}
/*
* Allows anyone to publish a message (an encrypted command and signature).
* This function also enqueues the message.
* @param _message The message to publish
* @param _encPubKey An epheremal public key which can be combined with the
* coordinator's private key to generate an ECDH shared key with which
* to encrypt the message.
*/
function publishMessage(
Message memory _message,
PubKey memory _encPubKey
) public {
uint256 secondsPassed = block.timestamp - deployTime;
require(
secondsPassed <= duration,
ERROR_VOTING_PERIOD_PASSED
);
require(
numMessages <= maxValues.maxMessages,
ERROR_MAX_MESSAGES_REACHED
);
require(
_encPubKey.x < SNARK_SCALAR_FIELD &&
_encPubKey.y < SNARK_SCALAR_FIELD,
ERROR_INVALID_PUBKEY
);
uint256 messageLeaf = hashMessageAndEncPubKey(_message, _encPubKey);
extContracts.messageAq.enqueue(messageLeaf);
numMessages ++;
emit PublishMessage(_message, _encPubKey);
}
function hashMessageAndEncPubKey(
Message memory _message,
PubKey memory _encPubKey
) public pure returns (uint256) {
uint256[5] memory n;
n[0] = _message.data[0];
n[1] = _message.data[1];
n[2] = _message.data[2];
n[3] = _message.data[3];
n[4] = _message.data[4];
uint256[5] memory m;
m[0] = _message.data[5];
m[1] = _message.data[6];
m[2] = _message.data[7];
m[3] = _message.data[8];
m[4] = _message.data[9];
return hash4([
hash5(n),
hash5(m),
_encPubKey.x,
_encPubKey.y
]);
}
/*
* The first step of merging the MACI state AccQueue. This allows the
* ProcessMessages circuit to access the latest state tree and ballots via
* currentSbCommitment.
*/
function mergeMaciStateAqSubRoots(
uint256 _numSrQueueOps,
uint256 _pollId
)
public
onlyOwner
isAfterVotingDeadline {
// This function can only be called once per Poll
require(!stateAqMerged, ERROR_STATE_AQ_ALREADY_MERGED);
if (!extContracts.maci.stateAq().subTreesMerged()) {
extContracts.maci.mergeStateAqSubRoots(_numSrQueueOps, _pollId);
}
emit MergeMaciStateAqSubRoots(_numSrQueueOps);
}
/*
* The second step of merging the MACI state AccQueue. This allows the
* ProcessMessages circuit to access the latest state tree and ballots via
* currentSbCommitment.
*/
function mergeMaciStateAq(
uint256 _pollId
)
public
onlyOwner
isAfterVotingDeadline {
// This function can only be called once per Poll after the voting
// deadline
require(!stateAqMerged, ERROR_STATE_AQ_ALREADY_MERGED);
require(extContracts.maci.stateAq().subTreesMerged(), ERROR_STATE_AQ_SUBTREES_NEED_MERGE);
extContracts.maci.mergeStateAq(_pollId);
stateAqMerged = true;
mergedStateRoot = extContracts.maci.getStateAqRoot();
// Set currentSbCommitment
uint256[3] memory sb;
sb[0] = mergedStateRoot;
sb[1] = emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1];
sb[2] = uint256(0);
currentSbCommitment = hash3(sb);
emit MergeMaciStateAq(mergedStateRoot);
}
/*
* The first step in merging the message AccQueue so that the
* ProcessMessages circuit can access the message root.
*/
function mergeMessageAqSubRoots(uint256 _numSrQueueOps)
public
onlyOwner
isAfterVotingDeadline {
extContracts.messageAq.mergeSubRoots(_numSrQueueOps);
emit MergeMessageAqSubRoots(_numSrQueueOps);
}
/*
* The second step in merging the message AccQueue so that the
* ProcessMessages circuit can access the message root.
*/
function mergeMessageAq()
public
onlyOwner
isAfterVotingDeadline {
uint256 root = extContracts.messageAq.merge(treeDepths.messageTreeDepth);
emit MergeMessageAq(root);
}
/*
* Enqueue a batch of messages.
*/
function batchEnqueueMessage(uint256 _messageSubRoot)
public
onlyOwner
isAfterVotingDeadline {
extContracts.messageAq.insertSubTree(_messageSubRoot);
// TODO: emit event
}
/*
* @notice Verify the number of spent voice credits from the tally.json
* @param _totalSpent spent field retrieved in the totalSpentVoiceCredits object
* @param _totalSpentSalt the corresponding salt in the totalSpentVoiceCredit object
* @return valid a boolean representing successful verification
*/
function verifySpentVoiceCredits(
uint256 _totalSpent,
uint256 _totalSpentSalt
) public view returns (bool) {
uint256 ballotRoot = hashLeftRight(_totalSpent, _totalSpentSalt);
return ballotRoot == emptyBallotRoots[treeDepths.voteOptionTreeDepth - 1];
}
/*
* @notice Verify the number of spent voice credits per vote option from the tally.json
* @param _voteOptionIndex the index of the vote option where credits were spent
* @param _spent the spent voice credits for a given vote option index
* @param _spentProof proof generated for the perVOSpentVoiceCredits
* @param _salt the corresponding salt given in the tally perVOSpentVoiceCredits object
* @return valid a boolean representing successful verification
*/
function verifyPerVOSpentVoiceCredits(
uint256 _voteOptionIndex,
uint256 _spent,
uint256[][] memory _spentProof,
uint256 _spentSalt
) public view returns (bool) {
uint256 computedRoot = computeMerkleRootFromPath(
treeDepths.voteOptionTreeDepth,
_voteOptionIndex,
_spent,
_spentProof
);
uint256 ballotRoot = hashLeftRight(computedRoot, _spentSalt);
uint256[3] memory sb;
sb[0] = mergedStateRoot;
sb[1] = ballotRoot;
sb[2] = uint256(0);
return currentSbCommitment == hash3(sb);
}
/*
* @notice Verify the result generated of the tally.json
* @param _voteOptionIndex the index of the vote option to verify the correctness of the tally
* @param _tallyResult Flattened array of the tally
* @param _tallyResultProof Corresponding proof of the tally result
* @param _tallyResultSalt the respective salt in the results object in the tally.json
* @param _spentVoiceCreditsHash hashLeftRight(number of spent voice credits, spent salt)
* @param _perVOSpentVoiceCreditsHash hashLeftRight(merkle root of the no spent voice credits per vote option, perVOSpentVoiceCredits salt)
* @param _tallyCommitment newTallyCommitment field in the tally.json
* @return valid a boolean representing successful verification
*/
function verifyTallyResult(
uint256 _voteOptionIndex,
uint256 _tallyResult,
uint256[][] memory _tallyResultProof,
uint256 _spentVoiceCreditsHash,
uint256 _perVOSpentVoiceCreditsHash,
uint256 _tallyCommitment
) public view returns (bool){
uint256 computedRoot = computeMerkleRootFromPath(
treeDepths.voteOptionTreeDepth,
_voteOptionIndex,
_tallyResult,
_tallyResultProof
);
uint256[3] memory tally;
tally[0] = computedRoot;
tally[1] = _spentVoiceCreditsHash;
tally[2] = _perVOSpentVoiceCreditsHash;
return hash3(tally) == _tallyCommitment;
}
function computeMerkleRootFromPath(
uint8 _depth,
uint256 _index,
uint256 _leaf,
uint256[][] memory _pathElements
) internal pure returns (uint256) {
uint256 pos = _index % LEAVES_PER_NODE;
uint256 current = _leaf;
uint8 k;
uint256[LEAVES_PER_NODE] memory level;
for (uint8 i = 0; i < _depth; i ++) {
for (uint8 j = 0; j < LEAVES_PER_NODE; j ++) {
if (j == pos) {
level[j] = current;
} else {
if (j > pos) {
k = j - 1;
} else {
k = j;
}
level[j] = _pathElements[i][k];
}
}
_index /= LEAVES_PER_NODE;
pos = _index % LEAVES_PER_NODE;
current = hash5(level);
}
return current;
}
}
contract PollProcessorAndTallyer is
Ownable, SnarkCommon, SnarkConstants, IPubKey, PollDeploymentParams{
// Error codes
string constant ERROR_VOTING_PERIOD_NOT_PASSED = "PptE01";
string constant ERROR_NO_MORE_MESSAGES = "PptE02";
string constant ERROR_MESSAGE_AQ_NOT_MERGED = "PptE03";
string constant ERROR_INVALID_STATE_ROOT_SNAPSHOT_TIMESTAMP = "PptE04";
string constant ERROR_INVALID_PROCESS_MESSAGE_PROOF = "PptE05";
string constant ERROR_INVALID_TALLY_VOTES_PROOF = "PptE06";
string constant ERROR_PROCESSING_NOT_COMPLETE = "PptE07";
string constant ERROR_ALL_BALLOTS_TALLIED = "PptE08";
string constant ERROR_STATE_AQ_NOT_MERGED = "PptE09";
string constant ERROR_ALL_SUBSIDY_CALCULATED = "PptE10";
string constant ERROR_INVALID_SUBSIDY_PROOF = "PptE11";
// The commitment to the state and ballot roots
uint256 public sbCommitment;
// The current message batch index. When the coordinator runs
// processMessages(), this action relates to messages
// currentMessageBatchIndex to currentMessageBatchIndex + messageBatchSize.
uint256 public currentMessageBatchIndex;
// Whether there are unprocessed messages left
bool public processingComplete;
// The number of batches processed
uint256 public numBatchesProcessed;
// The commitment to the tally results. Its initial value is 0, but after
// the tally of each batch is proven on-chain via a zk-SNARK, it should be
// updated to:
//
// hash3(
// hashLeftRight(merkle root of current results, salt0)
// hashLeftRight(number of spent voice credits, salt1),
// hashLeftRight(merkle root of the no. of spent voice credits per vote option, salt2)
// )
//
// Where each salt is unique and the merkle roots are of arrays of leaves
// TREE_ARITY ** voteOptionTreeDepth long.
uint256 public tallyCommitment;
uint256 public tallyBatchNum;
uint256 public subsidyCommitment;
uint256 public rbi; // row batch index
uint256 public cbi; // column batch index
Verifier public verifier;
constructor(
Verifier _verifier
) {
verifier = _verifier;
}
modifier votingPeriodOver(Poll _poll) {
(uint256 deployTime, uint256 duration) = _poll.getDeployTimeAndDuration();
// Require that the voting period is over
uint256 secondsPassed = block.timestamp - deployTime;
require(
secondsPassed > duration,
ERROR_VOTING_PERIOD_NOT_PASSED
);
_;
}
/*
* Hashes an array of values using SHA256 and returns its modulo with the
* snark scalar field. This function is used to hash inputs to circuits,
* where said inputs would otherwise be public inputs. As such, the only
* public input to the circuit is the SHA256 hash, and all others are
* private inputs. The circuit will verify that the hash is valid. Doing so
* saves a lot of gas during verification, though it makes the circuit take
* up more constraints.
*/
function sha256Hash(uint256[] memory array) public pure returns (uint256) {
return uint256(sha256(abi.encodePacked(array))) % SNARK_SCALAR_FIELD;
}
/*
* Update the Poll's currentSbCommitment if the proof is valid.
* @param _poll The poll to update
* @param _newSbCommitment The new state root and ballot root commitment
* after all messages are processed
* @param _proof The zk-SNARK proof
*/
function processMessages(
Poll _poll,
uint256 _newSbCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
// There must be unprocessed messages
require(!processingComplete, ERROR_NO_MORE_MESSAGES);
// The state AccQueue must be merged
require(_poll.stateAqMerged(), ERROR_STATE_AQ_NOT_MERGED);
// Retrieve stored vals
( , , uint8 messageTreeDepth,) = _poll.treeDepths();
(uint256 messageBatchSize,, ) = _poll.batchSizes();
AccQueue messageAq;
(, , messageAq) = _poll.extContracts();
// Require that the message queue has been merged
uint256 messageRoot = messageAq.getMainRoot(messageTreeDepth);
require(messageRoot != 0, ERROR_MESSAGE_AQ_NOT_MERGED);
// Copy the state and ballot commitment and set the batch index if this
// is the first batch to process
if (numBatchesProcessed == 0) {
uint256 currentSbCommitment = _poll.currentSbCommitment();
sbCommitment = currentSbCommitment;
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
uint256 r = numMessages % messageBatchSize;
if (r == 0) {
currentMessageBatchIndex =
(numMessages / messageBatchSize) * messageBatchSize;
} else {
currentMessageBatchIndex = numMessages;
}
if (currentMessageBatchIndex > 0) {
if (r == 0) {
currentMessageBatchIndex -= messageBatchSize;
} else {
currentMessageBatchIndex -= r;
}
}
}
bool isValid = verifyProcessProof(
_poll,
currentMessageBatchIndex,
messageRoot,
sbCommitment,
_newSbCommitment,
_proof
);
require(isValid, ERROR_INVALID_PROCESS_MESSAGE_PROOF);
{
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
// Decrease the message batch start index to ensure that each
// message batch is processed in order
if (currentMessageBatchIndex > 0) {
currentMessageBatchIndex -= messageBatchSize;
}
updateMessageProcessingData(
_newSbCommitment,
currentMessageBatchIndex,
numMessages <= messageBatchSize * (numBatchesProcessed + 1)
);
}
}
function verifyProcessProof(
Poll _poll,
uint256 _currentMessageBatchIndex,
uint256 _messageRoot,
uint256 _currentSbCommitment,
uint256 _newSbCommitment,
uint256[8] memory _proof
) internal view returns (bool) {
( , , uint8 messageTreeDepth, uint8 voteOptionTreeDepth) = _poll.treeDepths();
(uint256 messageBatchSize,,) = _poll.batchSizes();
(uint256 numSignUps, ) = _poll.numSignUpsAndMessages();
(VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts();
// Calculate the public input hash (a SHA256 hash of several values)
uint256 publicInputHash = genProcessMessagesPublicInputHash(
_poll,
_currentMessageBatchIndex,
_messageRoot,
numSignUps,
_currentSbCommitment,
_newSbCommitment
);
// Get the verifying key from the VkRegistry
VerifyingKey memory vk = vkRegistry.getProcessVk(
maci.stateTreeDepth(),
messageTreeDepth,
voteOptionTreeDepth,
messageBatchSize
);
return verifier.verify(_proof, vk, publicInputHash);
}
/*
* Returns the SHA256 hash of the packed values (see
* genProcessMessagesPackedVals), the hash of the coordinator's public key,
* the message root, and the commitment to the current state root and
* ballot root. By passing the SHA256 hash of these values to the circuit
* as a single public input and the preimage as private inputs, we reduce
* its verification gas cost though the number of constraints will be
* higher and proving time will be higher.
*/
function genProcessMessagesPublicInputHash(
Poll _poll,
uint256 _currentMessageBatchIndex,
uint256 _messageRoot,
uint256 _numSignUps,
uint256 _currentSbCommitment,
uint256 _newSbCommitment
) public view returns (uint256) {
uint256 coordinatorPubKeyHash = _poll.coordinatorPubKeyHash();
uint256 packedVals = genProcessMessagesPackedVals(
_poll,
_currentMessageBatchIndex,
_numSignUps
);
(uint256 deployTime, uint256 duration) = _poll.getDeployTimeAndDuration();
uint256[] memory input = new uint256[](6);
input[0] = packedVals;
input[1] = coordinatorPubKeyHash;
input[2] = _messageRoot;
input[3] = _currentSbCommitment;
input[4] = _newSbCommitment;
input[5] = deployTime + duration;
uint256 inputHash = sha256Hash(input);
return inputHash;
}
/*
* One of the inputs to the ProcessMessages circuit is a 250-bit
* representation of four 50-bit values. This function generates this
* 250-bit value, which consists of the maximum number of vote options, the
* number of signups, the current message batch index, and the end index of
* the current batch.
*/
function genProcessMessagesPackedVals(
Poll _poll,
uint256 _currentMessageBatchIndex,
uint256 _numSignUps
) public view returns (uint256) {
(, uint256 maxVoteOptions) = _poll.maxValues();
(, uint256 numMessages) = _poll.numSignUpsAndMessages();
(uint8 mbs,,) = _poll.batchSizes();
uint256 messageBatchSize = uint256(mbs);
uint256 batchEndIndex = _currentMessageBatchIndex + messageBatchSize;
if (batchEndIndex > numMessages) {
batchEndIndex = numMessages;
}
uint256 result =
maxVoteOptions +
(_numSignUps << uint256(50)) +
(_currentMessageBatchIndex << uint256(100)) +
(batchEndIndex << uint256(150));
return result;
}
function updateMessageProcessingData(
uint256 _newSbCommitment,
uint256 _currentMessageBatchIndex,
bool _processingComplete
) internal {
sbCommitment = _newSbCommitment;
processingComplete = _processingComplete;
currentMessageBatchIndex = _currentMessageBatchIndex;
numBatchesProcessed ++;
}
function genSubsidyPackedVals(uint256 _numSignUps) public view returns (uint256) {
// TODO: ensure that each value is less than or equal to 2 ** 50
uint256 result =
(_numSignUps << uint256(100)) +
(rbi << uint256(50))+
cbi;
return result;
}
function genSubsidyPublicInputHash(
uint256 _numSignUps,
uint256 _newSubsidyCommitment
) public view returns (uint256) {
uint256 packedVals = genSubsidyPackedVals(_numSignUps);
uint256[] memory input = new uint256[](4);
input[0] = packedVals;
input[1] = sbCommitment;
input[2] = subsidyCommitment;
input[3] = _newSubsidyCommitment;
uint256 inputHash = sha256Hash(input);
return inputHash;
}
function updateSubsidy(
Poll _poll,
uint256 _newSubsidyCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
// Require that all messages have been processed
require(
processingComplete,
ERROR_PROCESSING_NOT_COMPLETE
);
(uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths();
uint256 subsidyBatchSize = 5 ** intStateTreeDepth; // treeArity is fixed to 5
(uint256 numSignUps,) = _poll.numSignUpsAndMessages();
uint256 numLeaves = numSignUps + 1;
// Require that there are untalied ballots left
require(
rbi * subsidyBatchSize <= numLeaves,
ERROR_ALL_SUBSIDY_CALCULATED
);
require(
cbi * subsidyBatchSize <= numLeaves,
ERROR_ALL_SUBSIDY_CALCULATED
);
bool isValid = verifySubsidyProof(_poll,_proof,numSignUps, _newSubsidyCommitment);
require(isValid, ERROR_INVALID_SUBSIDY_PROOF);
subsidyCommitment = _newSubsidyCommitment;
increaseSubsidyIndex(subsidyBatchSize, numLeaves);
}
function increaseSubsidyIndex(uint256 batchSize, uint256 numLeaves) internal {
if (cbi * batchSize + batchSize < numLeaves) {
cbi++;
} else {
rbi++;
cbi = 0;
}
}
function verifySubsidyProof(
Poll _poll,
uint256[8] memory _proof,
uint256 _numSignUps,
uint256 _newSubsidyCommitment
) public view returns (bool) {
(uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths();
(VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts();
// Get the verifying key
VerifyingKey memory vk = vkRegistry.getSubsidyVk(
maci.stateTreeDepth(),
intStateTreeDepth,
voteOptionTreeDepth
);
// Get the public inputs
uint256 publicInputHash = genSubsidyPublicInputHash(_numSignUps, _newSubsidyCommitment);
// Verify the proof
return verifier.verify(_proof, vk, publicInputHash);
}
/*
* Pack the batch start index and number of signups into a 100-bit value.
*/
function genTallyVotesPackedVals(
uint256 _numSignUps,
uint256 _batchStartIndex,
uint256 _tallyBatchSize
) public pure returns (uint256) {
// TODO: ensure that each value is less than or equal to 2 ** 50
uint256 result =
(_batchStartIndex / _tallyBatchSize) +
(_numSignUps << uint256(50));
return result;
}
function genTallyVotesPublicInputHash(
uint256 _numSignUps,
uint256 _batchStartIndex,
uint256 _tallyBatchSize,
uint256 _newTallyCommitment
) public view returns (uint256) {
uint256 packedVals = genTallyVotesPackedVals(
_numSignUps,
_batchStartIndex,
_tallyBatchSize
);
uint256[] memory input = new uint256[](4);
input[0] = packedVals;
input[1] = sbCommitment;
input[2] = tallyCommitment;
input[3] = _newTallyCommitment;
uint256 inputHash = sha256Hash(input);
return inputHash;
}
function tallyVotes(
Poll _poll,
uint256 _newTallyCommitment,
uint256[8] memory _proof
)
public
onlyOwner
votingPeriodOver(_poll)
{
// Require that all messages have been processed
require(
processingComplete,
ERROR_PROCESSING_NOT_COMPLETE
);
( , uint256 tallyBatchSize,) = _poll.batchSizes();
uint256 batchStartIndex = tallyBatchNum * tallyBatchSize;
(uint256 numSignUps,) = _poll.numSignUpsAndMessages();
// Require that there are untalied ballots left
require(
batchStartIndex <= numSignUps,
ERROR_ALL_BALLOTS_TALLIED
);
bool isValid = verifyTallyProof(
_poll,
_proof,
numSignUps,
batchStartIndex,
tallyBatchSize,
_newTallyCommitment
);
require(isValid, ERROR_INVALID_TALLY_VOTES_PROOF);
// Update the tally commitment and the tally batch num
tallyCommitment = _newTallyCommitment;
tallyBatchNum ++;
}
/*
* @notice Verify the tally proof using the verifiying key
* @param _poll contract address of the poll proof to be verified
* @param _proof the proof generated after processing all messages
* @param _numSignUps number of signups for a given poll
* @param _batchStartIndex the number of batches multiplied by the size of the batch
* @param _tallyBatchSize batch size for the tally
* @param _newTallyCommitment the tally commitment to be verified at a given batch index
* @return valid a boolean representing successful verification
*/
function verifyTallyProof(
Poll _poll,
uint256[8] memory _proof,
uint256 _numSignUps,
uint256 _batchStartIndex,
uint256 _tallyBatchSize,
uint256 _newTallyCommitment
) public view returns (bool) {
(uint8 intStateTreeDepth,,,uint8 voteOptionTreeDepth) = _poll.treeDepths();
(VkRegistry vkRegistry, IMACI maci, ) = _poll.extContracts();
// Get the verifying key
VerifyingKey memory vk = vkRegistry.getTallyVk(
maci.stateTreeDepth(),
intStateTreeDepth,
voteOptionTreeDepth
);
// Get the public inputs
uint256 publicInputHash = genTallyVotesPublicInputHash(
_numSignUps,
_batchStartIndex,
_tallyBatchSize,
_newTallyCommitment
);
// Verify the proof
return verifier.verify(_proof, vk, publicInputHash);
}
}
| Verify the number of spent voice credits per vote option from the tally.json _voteOptionIndex the index of the vote option where credits were spent _spent the spent voice credits for a given vote option index _spentProof proof generated for the perVOSpentVoiceCredits _salt the corresponding salt given in the tally perVOSpentVoiceCredits object return valid a boolean representing successful verification/ | function verifyPerVOSpentVoiceCredits(
uint256 _voteOptionIndex,
uint256 _spent,
uint256[][] memory _spentProof,
uint256 _spentSalt
) public view returns (bool) {
uint256 computedRoot = computeMerkleRootFromPath(
treeDepths.voteOptionTreeDepth,
_voteOptionIndex,
_spent,
_spentProof
);
uint256 ballotRoot = hashLeftRight(computedRoot, _spentSalt);
uint256[3] memory sb;
sb[0] = mergedStateRoot;
sb[1] = ballotRoot;
sb[2] = uint256(0);
return currentSbCommitment == hash3(sb);
}
| 1,814,247 |
./full_match/5/0x8956E81d76FDdAbF0de54D8Da0d06c2474DeA340/sources/contracts/flatten.sol | Users can claim tokens for all projects they are signed up for Loop through all projects the user is signed up for and calculate claimable tokenstodo find a way to not fail | function batchClaim() external {
for (uint256 i = 0; i < s_userProjects[_msgSender()].length(); i++) {
_claim(s_userProjects[_msgSender()].at(i));
}
}
| 11,605,907 |
// SPDX-License-Identifier: None
pragma solidity ^0.8.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import './ERC2981.sol';
struct SaleConfig {
uint32 privateSaleStartTime;
uint32 preSaleStartTime;
uint32 publicSaleStartTime;
uint16 privateSaleSupplyLimit;
uint8 publicSaleTxLimit;
}
contract Mehtaverse is Ownable, ERC721, ERC2981 {
using SafeMath for uint256;
using SafeCast for uint256;
using ECDSA for bytes32;
uint256 public constant supplyLimit = 2222;
uint256 public mintPrice = 0.22 ether;
uint256 public totalSupply = 0;
SaleConfig public saleConfig;
address public whitelistSigner;
string public baseURI;
uint256 public constant PROVENANCE_HASH = 0xccab09c3e07e4927de0281c375526ee2317a38097955bf405e2dfd7cfb9fc59c;
uint256 public randomizedStartIndex;
mapping(address => uint) private presaleMinted;
address payable public withdrawalAddress;
bytes32 private DOMAIN_SEPARATOR;
bytes32 private PRIVATE_SALE_TYPEHASH = keccak256("privateSale(address buyer,uint256 limit)");
bytes32 private PRESALE_TYPEHASH = keccak256("presale(address buyer,uint256 limit)");
constructor(
string memory inputBaseUri,
address payable inputWithdrawalAddress
) ERC721("Mehtaverse", "MEH") {
baseURI = inputBaseUri;
withdrawalAddress = inputWithdrawalAddress;
saleConfig = SaleConfig({
privateSaleStartTime: 1635690120, //31 Oct 2021 22:22:00 UTC+0800
preSaleStartTime: 1635776520, //1 Nov 2021 22:22:00 UTC+0800
publicSaleStartTime: 1635862920, //2 Nov 2021 22:22:00 UTC+0800
privateSaleSupplyLimit: 267,
publicSaleTxLimit: 5
});
_setRoyalties(withdrawalAddress, 750); // 7.5% royalties
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("Mehtaverse")),
keccak256(bytes("1")),
chainId,
address(this))
);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory newBaseUri) external onlyOwner {
baseURI = newBaseUri;
}
function setWithdrawalAddress(address payable newAddress) external onlyOwner {
withdrawalAddress = newAddress;
}
function setMintPrice(uint newPrice) external onlyOwner {
mintPrice = newPrice;
}
function setWhiteListSigner(address signer) external onlyOwner {
whitelistSigner = signer;
}
function setRoyalties(address recipient, uint256 value) external onlyOwner {
require(recipient != address(0), "zero address");
_setRoyalties(recipient, value);
}
function configureSales(
uint256 privateSaleStartTime,
uint256 preSaleStartTime,
uint256 publicSaleStartTime,
uint256 privateSaleSupplyLimit,
uint256 publicSaleTxLimit
) external onlyOwner {
uint32 _privateSaleStartTime = privateSaleStartTime.toUint32();
uint32 _preSaleStartTime = preSaleStartTime.toUint32();
uint32 _publicSaleStartTime = publicSaleStartTime.toUint32();
uint16 _privateSaleSupplyLimit = privateSaleSupplyLimit.toUint16();
uint8 _publicSaleTxLimit = publicSaleTxLimit.toUint8();
require(0 < _privateSaleStartTime, "Invalid time");
require(_privateSaleStartTime < _preSaleStartTime, "Invalid time");
require(_preSaleStartTime < _publicSaleStartTime, "Invalid time");
saleConfig = SaleConfig({
privateSaleStartTime: _privateSaleStartTime,
preSaleStartTime: _preSaleStartTime,
publicSaleStartTime: _publicSaleStartTime,
privateSaleSupplyLimit: _privateSaleSupplyLimit,
publicSaleTxLimit: _publicSaleTxLimit
});
}
function buyPrivateSale(bytes memory signature, uint numberOfTokens, uint approvedLimit) external payable {
SaleConfig memory _saleConfig = saleConfig;
require(block.timestamp >= _saleConfig.privateSaleStartTime && block.timestamp < _saleConfig.preSaleStartTime, "Private sale not active");
require(whitelistSigner != address(0), "White list signer not yet set");
require(msg.value == mintPrice.mul(numberOfTokens), "Incorrect payment");
require((presaleMinted[msg.sender] + numberOfTokens) <= approvedLimit, "Wallet limit exceeded");
require((totalSupply + numberOfTokens) <= _saleConfig.privateSaleSupplyLimit, "Private sale limit exceeded");
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PRIVATE_SALE_TYPEHASH, msg.sender, approvedLimit))));
address signer = digest.recover(signature);
require(signer != address(0) && signer == whitelistSigner, "Invalid signature");
presaleMinted[msg.sender] = presaleMinted[msg.sender] + numberOfTokens;
mint(msg.sender, numberOfTokens);
}
function buyPresale(bytes memory signature, uint numberOfTokens, uint approvedLimit) external payable {
require(block.timestamp >= saleConfig.preSaleStartTime && block.timestamp < saleConfig.publicSaleStartTime, "Presale is not active");
require(whitelistSigner != address(0), "White list signer not yet set");
require(msg.value == mintPrice.mul(numberOfTokens), "Incorrect payment");
require((presaleMinted[msg.sender] + numberOfTokens) <= approvedLimit, "Wallet limit exceeded");
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PRESALE_TYPEHASH, msg.sender, approvedLimit))));
address signer = digest.recover(signature);
require(signer != address(0) && signer == whitelistSigner, "Invalid signature");
presaleMinted[msg.sender] = presaleMinted[msg.sender] + numberOfTokens;
mint(msg.sender, numberOfTokens);
}
function buy(uint numberOfTokens) external payable {
SaleConfig memory _saleConfig = saleConfig;
require(block.timestamp >= _saleConfig.publicSaleStartTime, "Sale is not active");
require(msg.value == mintPrice.mul(numberOfTokens), "Incorrect payment");
require(numberOfTokens <= _saleConfig.publicSaleTxLimit, "Transaction limit exceeded");
mint(msg.sender, numberOfTokens);
}
function mint(address to, uint numberOfTokens) private {
require(totalSupply.add(numberOfTokens) <= supplyLimit, "Not enough tokens left");
uint256 newId = totalSupply;
for(uint i = 0; i < numberOfTokens; i++) {
newId += 1;
_safeMint(to, newId);
}
totalSupply = newId;
}
function reserve(address to, uint256 numberOfTokens) external onlyOwner {
mint(to, numberOfTokens);
}
function rollStartIndex() external onlyOwner {
require(randomizedStartIndex == 0, 'Index already set');
require(block.timestamp >= saleConfig.publicSaleStartTime, "Too early to roll start index");
uint256 number = uint256(
keccak256(abi.encodePacked(blockhash(block.number - 1), block.coinbase, block.difficulty))
);
randomizedStartIndex = number % supplyLimit + 1;
}
function withdraw() external onlyOwner {
require(address(this).balance > 0, "No balance to withdraw");
(bool success, ) = withdrawalAddress.call{value: address(this).balance}("");
require(success, "Withdrawal failed");
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './IERC2981.sol';
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
contract ERC2981 is ERC165, IERC2981 {
struct RoyaltyInfo {
address recipient;
uint24 amount;
}
RoyaltyInfo private _royalties;
/// @dev Sets token royalties
/// @param recipient recipient of the royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(address recipient, uint256 value) internal {
require(value <= 10000, 'ERC2981Royalties: Too high');
_royalties = RoyaltyInfo(recipient, uint24(value));
}
/// @inheritdoc IERC2981
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (value * royalties.amount) / 10000;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: None
pragma solidity ^0.8.8;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
} | Interface for the NFT Royalty Standard is owed and to whom. | interface IERC2981 {
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
}
pragma solidity ^0.8.8;
} | 14,376,165 |
// "SPDX-License-Identifier: MIT"
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./vendors/interfaces/IERC20.sol";
import "./vendors/interfaces/IDelegableERC20.sol";
import "./vendors/libraries/SafeMath.sol";
import "./vendors/libraries/SafeERC20.sol";
import "./vendors/contracts/access/Ownable.sol";
contract TeamPoolPACT is Ownable{
using SafeMath for uint;
using SafeERC20 for IERC20;
event Withdraw(uint tokensAmount);
address public _PACT;
uint constant oneYear = 365 days;
uint[2][4] private annualSupplyPoints = [
[block.timestamp, 12500000e18],
[block.timestamp.add(oneYear.mul(1)), 12500000e18],
[block.timestamp.add(oneYear.mul(2)), 12500000e18],
[block.timestamp.add(oneYear.mul(3)), 12500000e18]
];
/**
* @dev Initializes the contract setting the deployer as the initial owner (`ownerAddress`)
* and pact contract address (`PACT`).
*/
constructor (
address ownerAddress,
address PACT
) public {
require (PACT != address(0), "PACT ADDRESS SHOULD BE NOT NULL");
_PACT = PACT;
transferOwnership(ownerAddress == address(0) ? msg.sender : ownerAddress);
IDelegableERC20(_PACT).delegate(ownerAddress);
}
/**
* @dev Returns the annual supply points of the current contract.
*/
function getReleases() external view returns(uint[2][4] memory) {
return annualSupplyPoints;
}
/**
* @dev Withdrawal tokens the address (`to`) and amount (`amount`).
* Can only be called by the current owner.
*/
function withdraw(address to,uint amount) external onlyOwner {
IERC20 PACT = IERC20(_PACT);
require (to != address(0), "ADDRESS SHOULD BE NOT NULL");
require(amount <= PACT.balanceOf(address(this)), "NOT ENOUGH PACT TOKENS ON TEAMPOOL CONTRACT BALANCE");
for(uint i; i < 4; i++) {
if(annualSupplyPoints[i][1] >= amount && block.timestamp >= annualSupplyPoints[i][0]) {
annualSupplyPoints[i][1] = annualSupplyPoints[i][1].sub(amount);
PACT.safeTransfer(to, amount);
return ;
}
}
require (false, "TokenTimelock: no tokens to release");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../utils/Context.sol";
// Copied from OpenZeppelin code:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
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() public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Copied from OpenZeppelin code:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol
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.6.12;
interface IDelegable {
function delegate(address delegatee) external;
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function getCurrentVotes(address account) external view returns (uint256);
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IDelegable.sol";
import "./IERC20WithMaxTotalSupply.sol";
interface IDelegableERC20 is IDelegable, IERC20WithMaxTotalSupply {}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function approve(address spender, uint tokens) external returns (bool success);
function transfer(address to, 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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC20.sol";
interface IERC20WithMaxTotalSupply is IERC20 {
event Mint(address indexed account, uint tokens);
event Burn(address indexed account, uint tokens);
function maxTotalSupply() external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IERC20.sol";
library SafeERC20 {
function safeSymbol(IERC20 token) internal view returns(string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeName(IERC20 token) internal view returns(string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeDecimals(IERC20 token) public view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
function safeTransfer(IERC20 token, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed");
}
function safeApprove(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransferFrom(IERC20 token, address from, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return add(a, b, "SafeMath: Add Overflow");
}
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);// "SafeMath: Add Overflow"
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: Underflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;// "SafeMath: Underflow"
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return mul(a, b, "SafeMath: Mul Overflow");
}
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);// "SafeMath: Mul Overflow"
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
| Returns the annual supply points of the current contract./ | function getReleases() external view returns(uint[2][4] memory) {
return annualSupplyPoints;
}
| 12,099,646 |
./partial_match/1/0xAAE149B45ac2FD5744aB2E5599198e49d6C4feC6/sources/FORSAKEN.sol | loop on the top wallets, only saving out the top 2 | function manualEstablishThirteenKeys() external onlyOwner {
require(!thirteenKeysEstablished, "thirteen already established");
for (uint i = 0; i < keyHolders.length; i++) {
tempBalances.push(_rOwned[keyHolders[i]]);
}
sorter();
for (uint i = 0; i < 2; i ++) {
for (uint x = 0; x < keyHolders.length; x++) {
if (_rOwned[keyHolders[x]] == tempBalances[i]) {
thirteenKeys.push(keyHolders[x]);
}
}
}
thirteenKeysEstablished = true;
}
| 4,307,655 |
/**
*Submitted for verification at Etherscan.io on 2021-04-01
*/
// File: contracts\modules\SafeMath.sol
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'SafeMath: addition overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'SafeMath: substraction underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'SafeMath: multiplication overflow');
}
}
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\modules\Managerable.sol
pragma solidity =0.5.16;
contract Managerable is Ownable {
address private _managerAddress;
/**
* @dev modifier, Only manager can be granted exclusive access to specific functions.
*
*/
modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
/**
* @dev set manager by owner.
*
*/
function setManager(address managerAddress)
public
onlyOwner
{
_managerAddress = managerAddress;
}
/**
* @dev get manager address.
*
*/
function getManager()public view returns (address) {
return _managerAddress;
}
}
// File: contracts\modules\Halt.sol
pragma solidity =0.5.16;
contract Halt is Ownable {
bool private halted = false;
modifier notHalted() {
require(!halted,"This contract is halted");
_;
}
modifier isHalted() {
require(halted,"This contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts\modules\whiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist which filters a eligible uint32.
*/
library whiteListUint32 {
/**
* @dev add uint32 into white list.
* @param whiteList the storage whiteList.
* @param temp input value
*/
function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
if (!isEligibleUint32(whiteList,temp)){
whiteList.push(temp);
}
}
/**
* @dev remove uint32 from whitelist.
*/
function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible uint256.
*/
library whiteListUint256 {
// add whiteList
function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
if (!isEligibleUint256(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible address.
*/
library whiteListAddress {
// add whiteList
function addWhiteListAddress(address[] storage whiteList,address temp) internal{
if (!isEligibleAddress(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
// File: contracts\modules\AddressWhiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist filters a eligible address.
*/
contract AddressWhiteList is Halt {
using whiteListAddress for address[];
uint256 constant internal allPermission = 0xffffffff;
uint256 constant internal allowBuyOptions = 1;
uint256 constant internal allowSellOptions = 1<<1;
uint256 constant internal allowExerciseOptions = 1<<2;
uint256 constant internal allowAddCollateral = 1<<3;
uint256 constant internal allowRedeemCollateral = 1<<4;
// The eligible adress list
address[] internal whiteList;
mapping(address => uint256) internal addressPermission;
/**
* @dev Implementation of add an eligible address into the whitelist.
* @param addAddress new eligible address.
*/
function addWhiteList(address addAddress)public onlyOwner{
whiteList.addWhiteListAddress(addAddress);
addressPermission[addAddress] = allPermission;
}
function modifyPermission(address addAddress,uint256 permission)public onlyOwner{
addressPermission[addAddress] = permission;
}
/**
* @dev Implementation of revoke an invalid address from the whitelist.
* @param removeAddress revoked address.
*/
function removeWhiteList(address removeAddress)public onlyOwner returns (bool){
addressPermission[removeAddress] = 0;
return whiteList.removeWhiteListAddress(removeAddress);
}
/**
* @dev Implementation of getting the eligible whitelist.
*/
function getWhiteList()public view returns (address[] memory){
return whiteList;
}
/**
* @dev Implementation of testing whether the input address is eligible.
* @param tmpAddress input address for testing.
*/
function isEligibleAddress(address tmpAddress) public view returns (bool){
return whiteList.isEligibleAddress(tmpAddress);
}
function checkAddressPermission(address tmpAddress,uint256 state) public view returns (bool){
return (addressPermission[tmpAddress]&state) == state;
}
}
// File: contracts\modules\ReentrancyGuard.sol
pragma solidity =0.5.16;
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancyLock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
// File: contracts\FNXMinePool\MinePoolData.sol
pragma solidity =0.5.16;
/**
* @title FPTCoin mine pool, which manager contract is FPTCoin.
* @dev A smart-contract which distribute some mine coins by FPTCoin balance.
*
*/
contract MinePoolData is Managerable,AddressWhiteList,ReentrancyGuard {
//Special decimals for calculation
uint256 constant calDecimals = 1e18;
// miner's balance
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerBalances;
// miner's origins, specially used for mine distribution
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerOrigins;
// mine coins total worth, specially used for mine distribution
mapping(address=>uint256) internal totalMinedWorth;
// total distributed mine coin amount
mapping(address=>uint256) internal totalMinedCoin;
// latest time to settlement
mapping(address=>uint256) internal latestSettleTime;
//distributed mine amount
mapping(address=>uint256) internal mineAmount;
//distributed time interval
mapping(address=>uint256) internal mineInterval;
//distributed mine coin amount for buy options user.
mapping(address=>uint256) internal buyingMineMap;
// user's Opterator indicator
uint256 constant internal opBurnCoin = 1;
uint256 constant internal opMintCoin = 2;
uint256 constant internal opTransferCoin = 3;
/**
* @dev Emitted when `account` mint `amount` miner shares.
*/
event MintMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `account` burn `amount` miner shares.
*/
event BurnMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `from` redeem `value` mineCoins.
*/
event RedeemMineCoin(address indexed from, address indexed mineCoin, uint256 value);
/**
* @dev Emitted when `from` transfer to `to` `amount` mineCoins.
*/
event TranserMiner(address indexed from, address indexed to, uint256 amount);
/**
* @dev Emitted when `account` buying options get `amount` mineCoins.
*/
event BuyingMiner(address indexed account,address indexed mineCoin,uint256 amount);
}
// File: contracts\ERC20\IERC20.sol
pragma solidity =0.5.16;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\FNXMinePool\FNXMinePool.sol
pragma solidity =0.5.16;
/**
* @title FPTCoin mine pool, which manager contract is FPTCoin.
* @dev A smart-contract which distribute some mine coins by FPTCoin balance.
*
*/
contract FNXMinePool is MinePoolData {
using SafeMath for uint256;
constructor () public{
initialize();
}
function initialize() onlyOwner public{
}
function update() onlyOwner public{
}
/**
* @dev default function for foundation input miner coins.
*/
function()external payable{
}
/**
* @dev foundation redeem out mine coins.
* @param mineCoin mineCoin address
* @param amount redeem amount.
*/
function redeemOut(address mineCoin,uint256 amount)public onlyOwner{
if (mineCoin == address(0)){
msg.sender.transfer(amount);
}else{
IERC20 token = IERC20(mineCoin);
uint256 preBalance = token.balanceOf(address(this));
token.transfer(msg.sender,amount);
uint256 afterBalance = token.balanceOf(address(this));
require(preBalance - afterBalance == amount,"settlement token transfer error!");
}
}
/**
* @dev retrieve total distributed mine coins.
* @param mineCoin mineCoin address
*/
function getTotalMined(address mineCoin)public view returns(uint256){
uint256 _totalSupply = totalSupply();
uint256 _mineInterval = mineInterval[mineCoin];
if (_totalSupply > 0 && _mineInterval>0){
uint256 _mineAmount = mineAmount[mineCoin];
uint256 latestMined = _mineAmount.mul(now-latestSettleTime[mineCoin])/_mineInterval;
return totalMinedCoin[mineCoin].add(latestMined);
}
return totalMinedCoin[mineCoin];
}
/**
* @dev retrieve minecoin distributed informations.
* @param mineCoin mineCoin address
* @return distributed amount and distributed time interval.
*/
function getMineInfo(address mineCoin)public view returns(uint256,uint256){
return (mineAmount[mineCoin],mineInterval[mineCoin]);
}
/**
* @dev retrieve user's mine balance.
* @param account user's account
* @param mineCoin mineCoin address
*/
function getMinerBalance(address account,address mineCoin)public view returns(uint256){
uint256 totalBalance = minerBalances[mineCoin][account];
uint256 _totalSupply = totalSupply();
uint256 balance = balanceOf(account);
if (_totalSupply > 0 && balance>0){
uint256 tokenNetWorth = _getCurrentTokenNetWorth(mineCoin);
totalBalance= totalBalance.add(_settlement(mineCoin,account,balance,tokenNetWorth));
}
return totalBalance;
}
/**
* @dev Set mineCoin mine info, only foundation owner can invoked.
* @param mineCoin mineCoin address
* @param _mineAmount mineCoin distributed amount
* @param _mineInterval mineCoin distributied time interval
*/
function setMineCoinInfo(address mineCoin,uint256 _mineAmount,uint256 _mineInterval)public onlyOwner {
require(_mineAmount<1e30,"input mine amount is too large");
require(_mineInterval>0,"input mine Interval must larger than zero");
_mineSettlement(mineCoin);
mineAmount[mineCoin] = _mineAmount;
mineInterval[mineCoin] = _mineInterval;
addWhiteList(mineCoin);
}
/**
* @dev Set the reward for buying options.
* @param mineCoin mineCoin address
* @param _mineAmount mineCoin reward amount
*/
function setBuyingMineInfo(address mineCoin,uint256 _mineAmount)public onlyOwner {
// require(_mineAmount<1e30,"input mine amount is too large");
buyingMineMap[mineCoin] = _mineAmount;
addWhiteList(mineCoin);
}
/**
* @dev Get the reward for buying options.
* @param mineCoin mineCoin address
*/
function getBuyingMineInfo(address mineCoin)public view returns(uint256){
return buyingMineMap[mineCoin];
}
/**
* @dev Get the all rewards for buying options.
*/
function getBuyingMineInfoAll()public view returns(address[] memory,uint256[] memory){
uint256 len = whiteList.length;
address[] memory mineCoins = new address[](len);
uint256[] memory mineNums = new uint256[](len);
for (uint256 i=0;i<len;i++){
mineCoins[i] = whiteList[i];
mineNums[i] = buyingMineMap[mineCoins[i]];
}
return (mineCoins,mineNums);
}
/**
* @dev transfer mineCoin to recieptor when account transfer amount FPTCoin to recieptor, only manager contract can modify database.
* @param account the account transfer from
* @param recieptor the account transfer to
* @param amount the mine shared amount
*/
function transferMinerCoin(address account,address recieptor,uint256 amount) public onlyManager {
_mineSettlementAll();
_transferMinerCoin(account,recieptor,amount);
}
/**
* @dev mint mineCoin to account when account add collateral to collateral pool, only manager contract can modify database.
* @param account user's account
* @param amount the mine shared amount
*/
function mintMinerCoin(address account,uint256 amount) public onlyManager {
_mineSettlementAll();
_mintMinerCoin(account,amount);
emit MintMiner(account,amount);
}
/**
* @dev Burn mineCoin to account when account redeem collateral to collateral pool, only manager contract can modify database.
* @param account user's account
* @param amount the mine shared amount
*/
function burnMinerCoin(address account,uint256 amount) public onlyManager {
_mineSettlementAll();
_burnMinerCoin(account,amount);
emit BurnMiner(account,amount);
}
/**
* @dev give amount buying reward to account, only manager contract can modify database.
* @param account user's account
* @param amount the buying shared amount
*/
function addMinerBalance(address account,uint256 amount) public onlyManager {
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
address addr = whiteList[i];
uint256 mineNum = buyingMineMap[addr];
if (mineNum > 0){
uint128 mineRate = uint128(mineNum);
uint128 mineAdd = uint128(mineNum>>128);
uint256 _mineAmount = mineRate*amount/calDecimals + mineAdd;
minerBalances[addr][account] = minerBalances[addr][account].add(_mineAmount);
//totalMinedCoin[addr] = totalMinedCoin[addr].add(_mineAmount);
emit BuyingMiner(account,addr,_mineAmount);
}
}
}
/**
* @dev changer mine coin distributed amount , only foundation owner can modify database.
* @param mineCoin mine coin address
* @param _mineAmount the distributed amount.
*/
function setMineAmount(address mineCoin,uint256 _mineAmount)public onlyOwner {
require(_mineAmount<1e30,"input mine amount is too large");
_mineSettlement(mineCoin);
mineAmount[mineCoin] = _mineAmount;
}
/**
* @dev changer mine coin distributed time interval , only foundation owner can modify database.
* @param mineCoin mine coin address
* @param _mineInterval the distributed time interval.
*/
function setMineInterval(address mineCoin,uint256 _mineInterval)public onlyOwner {
require(_mineInterval>0,"input mine Interval must larger than zero");
_mineSettlement(mineCoin);
mineInterval[mineCoin] = _mineInterval;
}
/**
* @dev user redeem mine rewards.
* @param mineCoin mine coin address
* @param amount redeem amount.
*/
function redeemMinerCoin(address mineCoin,uint256 amount)public nonReentrant notHalted {
_mineSettlement(mineCoin);
_settlementAllCoin(mineCoin,msg.sender);
uint256 minerAmount = minerBalances[mineCoin][msg.sender];
require(minerAmount>=amount,"miner balance is insufficient");
minerBalances[mineCoin][msg.sender] = minerAmount-amount;
_redeemMineCoin(mineCoin,msg.sender,amount);
}
/**
* @dev subfunction for user redeem mine rewards.
* @param mineCoin mine coin address
* @param recieptor recieptor's account
* @param amount redeem amount.
*/
function _redeemMineCoin(address mineCoin,address payable recieptor,uint256 amount)internal {
if (amount == 0){
return;
}
if (mineCoin == address(0)){
recieptor.transfer(amount);
}else{
IERC20 minerToken = IERC20(mineCoin);
uint256 preBalance = minerToken.balanceOf(address(this));
minerToken.transfer(recieptor,amount);
uint256 afterBalance = minerToken.balanceOf(address(this));
require(preBalance - afterBalance == amount,"settlement token transfer error!");
}
emit RedeemMineCoin(recieptor,mineCoin,amount);
}
/**
* @dev settle all mine coin.
*/
function _mineSettlementAll()internal{
uint256 addrLen = whiteList.length;
for(uint256 i=0;i<addrLen;i++){
_mineSettlement(whiteList[i]);
}
}
/**
* @dev the auxiliary function for _mineSettlementAll.
*/
function _mineSettlement(address mineCoin)internal{
uint256 latestMined = _getLatestMined(mineCoin);
uint256 _mineInterval = mineInterval[mineCoin];
if (latestMined>0){
totalMinedWorth[mineCoin] = totalMinedWorth[mineCoin].add(latestMined.mul(calDecimals));
totalMinedCoin[mineCoin] = totalMinedCoin[mineCoin]+latestMined;
}
if (_mineInterval>0){
latestSettleTime[mineCoin] = now/_mineInterval*_mineInterval;
}else{
latestSettleTime[mineCoin] = now;
}
}
/**
* @dev the auxiliary function for _mineSettlementAll. Calculate latest time phase distributied mine amount.
*/
function _getLatestMined(address mineCoin)internal view returns(uint256){
uint256 _mineInterval = mineInterval[mineCoin];
uint256 _totalSupply = totalSupply();
if (_totalSupply > 0 && _mineInterval>0){
uint256 _mineAmount = mineAmount[mineCoin];
uint256 mintTime = (now-latestSettleTime[mineCoin])/_mineInterval;
uint256 latestMined = _mineAmount*mintTime;
return latestMined;
}
return 0;
}
/**
* @dev subfunction, transfer mineCoin to recieptor when account transfer amount FPTCoin to recieptor
* @param account the account transfer from
* @param recipient the account transfer to
* @param amount the mine shared amount
*/
function _transferMinerCoin(address account,address recipient,uint256 amount)internal{
uint256 addrLen = whiteList.length;
for(uint256 i=0;i<addrLen;i++){
settleMinerBalance(whiteList[i],account,recipient,amount,opTransferCoin);
}
emit TranserMiner(account,recipient,amount);
}
/**
* @dev subfunction, mint mineCoin to account when account add collateral to collateral pool
* @param account user's account
* @param amount the mine shared amount
*/
function _mintMinerCoin(address account,uint256 amount)internal{
uint256 addrLen = whiteList.length;
for(uint256 i=0;i<addrLen;i++){
settleMinerBalance(whiteList[i],account,address(0),amount,opMintCoin);
}
}
/**
* @dev subfunction, settle user's mint balance when user want to modify mine database.
* @param mineCoin the mine coin address
* @param account user's account
*/
function _settlementAllCoin(address mineCoin,address account)internal{
settleMinerBalance(mineCoin,account,address(0),0,0);
}
/**
* @dev subfunction, Burn mineCoin to account when account redeem collateral to collateral pool
* @param account user's account
* @param amount the mine shared amount
*/
function _burnMinerCoin(address account,uint256 amount)internal{
uint256 addrLen = whiteList.length;
for(uint256 i=0;i<addrLen;i++){
settleMinerBalance(whiteList[i],account,address(0),amount,opBurnCoin);
}
}
/**
* @dev settle user's mint balance when user want to modify mine database.
* @param mineCoin the mine coin address
* @param account user's account
* @param recipient the recipient's address if operator is transfer
* @param amount the input amount for operator
* @param operators User operator to modify mine database.
*/
function settleMinerBalance(address mineCoin,address account,address recipient,uint256 amount,uint256 operators)internal{
uint256 _totalSupply = totalSupply();
uint256 tokenNetWorth = _getTokenNetWorth(mineCoin);
if (_totalSupply > 0){
minerBalances[mineCoin][account] = minerBalances[mineCoin][account].add(
_settlement(mineCoin,account,balanceOf(account),tokenNetWorth));
if (operators == opBurnCoin){
totalMinedWorth[mineCoin] = totalMinedWorth[mineCoin].sub(tokenNetWorth.mul(amount));
}else if (operators==opMintCoin){
totalMinedWorth[mineCoin] = totalMinedWorth[mineCoin].add(tokenNetWorth.mul(amount));
}else if (operators==opTransferCoin){
minerBalances[mineCoin][recipient] = minerBalances[mineCoin][recipient].add(
_settlement(mineCoin,recipient,balanceOf(recipient),tokenNetWorth));
minerOrigins[mineCoin][recipient] = tokenNetWorth;
}
}
minerOrigins[mineCoin][account] = tokenNetWorth;
}
/**
* @dev subfunction, settle user's latest mine amount.
* @param mineCoin the mine coin address
* @param account user's account
* @param amount the input amount for operator
* @param tokenNetWorth the latest token net worth
*/
function _settlement(address mineCoin,address account,uint256 amount,uint256 tokenNetWorth)internal view returns (uint256) {
uint256 origin = minerOrigins[mineCoin][account];
require(tokenNetWorth>=origin,"error: tokenNetWorth logic error!");
return amount.mul(tokenNetWorth-origin)/calDecimals;
}
/**
* @dev subfunction, calculate current token net worth.
* @param mineCoin the mine coin address
*/
function _getCurrentTokenNetWorth(address mineCoin)internal view returns (uint256) {
uint256 latestMined = _getLatestMined(mineCoin);
uint256 _totalSupply = totalSupply();
if (_totalSupply > 0){
return (totalMinedWorth[mineCoin].add(latestMined*calDecimals))/_totalSupply;
}
return 0;
}
/**
* @dev subfunction, calculate token net worth when settlement is completed.
* @param mineCoin the mine coin address
*/
function _getTokenNetWorth(address mineCoin)internal view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply > 0){
return totalMinedWorth[mineCoin]/_totalSupply;
}
return 0;
}
/**
* @dev get FPTCoin's total supply.
*/
function totalSupply()internal view returns(uint256){
IERC20 _FPTCoin = IERC20(getManager());
return _FPTCoin.totalSupply();
}
/**
* @dev get FPTCoin's user balance.
*/
function balanceOf(address account)internal view returns(uint256){
IERC20 _FPTCoin = IERC20(getManager());
return _FPTCoin.balanceOf(account);
}
} | default function for foundation input miner coins./ | function()external payable{
}
| 2,437,778 |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/crowdsale/IIvoCrowdsale.sol
/**
* @title Interface of IVO Crowdale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IIvoCrowdsale {
/**
* @return The starting time of the crowdsale.
*/
function startingTime() public view returns(uint256);
}
// File: contracts/vault/IVault.sol
/*
* @title Interface for basic vaults
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IVault {
/**
* @notice Adding beneficiary to the vault
* @param beneficiary The account that receives token
* @param value The amount of token allocated
*/
function receiveFor(address beneficiary, uint256 value) public;
/**
* @notice Update the releaseTime for vaults
* @param roundEndTime The new releaseTime
*/
function updateReleaseTime(uint256 roundEndTime) public;
}
// File: contracts/property/CounterGuard.sol
/**
* @title modifier contract that guards certain properties only triggered once
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CounterGuard {
/**
* @notice Controle if a boolean attribute (false by default) was updated to true.
* @dev This attribute is designed specifically for recording an action.
* @param criterion The boolean attribute that records if an action has taken place
*/
modifier onlyOnce(bool criterion) {
require(criterion == false, "Already been set");
_;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/property/Reclaimable.sol
/**
* @title Reclaimable
* @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to
* the token contract. The recovered token will be sent to the owner of token.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Reclaimable is Ownable {
using SafeERC20 for IERC20;
/**
* @notice Let the owner to retrieve other tokens accidentally sent to this contract.
* @dev This function is suitable when no token of any kind shall be stored under
* the address of the inherited contract.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.5.0;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/membership/ManagerRole.sol
/**
* @title Manager Role
* @dev This contract is developed based on the Manager contract of OpenZeppelin.
* The key difference is the management of the manager roles is restricted to one owner
* account. At least one manager should exist in any situation.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ManagerRole is Ownable {
using Roles for Roles.Role;
using SafeMath for uint256;
event ManagerAdded(address indexed account);
event ManagerRemoved(address indexed account);
Roles.Role private managers;
uint256 private _numManager;
constructor() internal {
_addManager(msg.sender);
_numManager = 1;
}
/**
* @notice Only manager can take action
*/
modifier onlyManager() {
require(isManager(msg.sender), "The account is not a manager");
_;
}
/**
* @notice This function allows to add managers in batch with control of the number of
* interations
* @param accounts The accounts to be added in batch
*/
// solhint-disable-next-line
function addManagers(address[] calldata accounts) external onlyOwner {
uint256 length = accounts.length;
require(length <= 256, "too many accounts");
for (uint256 i = 0; i < length; i++) {
_addManager(accounts[i]);
}
}
/**
* @notice Add an account to the list of managers,
* @param account The account address whose manager role needs to be removed.
*/
function removeManager(address account) external onlyOwner {
_removeManager(account);
}
/**
* @notice Check if an account is a manager
* @param account The account to be checked if it has a manager role
* @return true if the account is a manager. Otherwise, false
*/
function isManager(address account) public view returns (bool) {
return managers.has(account);
}
/**
*@notice Get the number of the current managers
*/
function numManager() public view returns (uint256) {
return _numManager;
}
/**
* @notice Add an account to the list of managers,
* @param account The account that needs to tbe added as a manager
*/
function addManager(address account) public onlyOwner {
require(account != address(0), "account is zero");
_addManager(account);
}
/**
* @notice Renounce the manager role
* @dev This function was not explicitly required in the specs. There should be at
* least one manager at any time. Therefore, at least two when one manage renounces
* themselves.
*/
function renounceManager() public {
require(_numManager >= 2, "Managers are fewer than 2");
_removeManager(msg.sender);
}
/** OVERRIDE
* @notice Allows the current owner to relinquish control of the contract.
* @dev 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 {
revert("Cannot renounce ownership");
}
/**
* @notice Internal function to be called when adding a manager
* @param account The address of the manager-to-be
*/
function _addManager(address account) internal {
_numManager = _numManager.add(1);
managers.add(account);
emit ManagerAdded(account);
}
/**
* @notice Internal function to remove one account from the manager list
* @param account The address of the to-be-removed manager
*/
function _removeManager(address account) internal {
_numManager = _numManager.sub(1);
managers.remove(account);
emit ManagerRemoved(account);
}
}
// File: contracts/membership/PausableManager.sol
/**
* @title Pausable Manager Role
* @dev This manager can also pause a contract. This contract is developed based on the
* Pause contract of OpenZeppelin.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableManager is ManagerRole {
event BePaused(address manager);
event BeUnpaused(address manager);
bool private _paused; // If the crowdsale contract is paused, controled by the manager...
constructor() internal {
_paused = false;
}
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "not paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "paused");
_;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @notice called by the owner to pause, triggers stopped state
*/
function pause() public onlyManager whenNotPaused {
_paused = true;
emit BePaused(msg.sender);
}
/**
* @notice called by the owner to unpause, returns to normal state
*/
function unpause() public onlyManager whenPaused {
_paused = false;
emit BeUnpaused(msg.sender);
}
}
// File: contracts/property/ValidAddress.sol
/**
* @title modifier contract that checks if the address is valid
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ValidAddress {
/**
* @notice Check if the address is not zero
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Not a valid address");
_;
}
/**
* @notice Check if the address is not the sender's address
*/
modifier isSenderNot(address _address) {
require(_address != msg.sender, "Address is the same as the sender");
_;
}
/**
* @notice Check if the address is the sender's address
*/
modifier isSender(address _address) {
require(_address == msg.sender, "Address is different from the sender");
_;
}
}
// File: contracts/membership/Whitelist.sol
/**
* @title Whitelist
* @dev The WhitelistCrowdsale was not included in OZ's release at the moment of the
* development of this contract. Therefore, we've developed the Whitelist contract and
* the WhitelistCrowdsale contract.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Whitelist is ValidAddress, PausableManager {
bool private _isWhitelisting;
mapping (address => bool) private _isWhitelisted;
event AddedWhitelisted(address indexed account);
event RemovedWhitelisted(address indexed account);
/**
* @notice Adding account control, only whitelisted accounts could do certain actions.
* @dev Whitelisting is enabled by default, There is not even the opportunity to
* disable it.
*/
constructor() internal {
_isWhitelisting = true;
}
/**
* @dev Add an account to the whitelist, calling the corresponding internal function
* @param account The address of the investor
*/
function addWhitelisted(address account) external onlyManager {
_addWhitelisted(account);
}
/**
* @notice This function allows to whitelist investors in batch
* with control of number of interations
* @param accounts The accounts to be whitelisted in batch
*/
// solhint-disable-next-line
function addWhitelisteds(address[] calldata accounts) external onlyManager {
uint256 length = accounts.length;
require(length <= 256, "too long");
for (uint256 i = 0; i < length; i++) {
_addWhitelisted(accounts[i]);
}
}
/**
* @notice Remove an account from the whitelist, calling the corresponding internal
* function
* @param account The address of the investor that needs to be removed
*/
function removeWhitelisted(address account)
external
onlyManager
{
_removeWhitelisted(account);
}
/**
* @notice This function allows to whitelist investors in batch
* with control of number of interations
* @param accounts The accounts to be whitelisted in batch
*/
// solhint-disable-next-line
function removeWhitelisteds(address[] calldata accounts)
external
onlyManager
{
uint256 length = accounts.length;
require(length <= 256, "too long");
for (uint256 i = 0; i < length; i++) {
_removeWhitelisted(accounts[i]);
}
}
/**
* @notice Check if an account is whitelisted or not
* @param account The account to be checked
* @return true if the account is whitelisted. Otherwise, false.
*/
function isWhitelisted(address account) public view returns (bool) {
return _isWhitelisted[account];
}
/**
* @notice Add an investor to the whitelist
* @param account The address of the investor that has successfully passed KYC
*/
function _addWhitelisted(address account)
internal
onlyValidAddress(account)
{
require(_isWhitelisted[account] == false, "account already whitelisted");
_isWhitelisted[account] = true;
emit AddedWhitelisted(account);
}
/**
* @notice Remove an investor from the whitelist
* @param account The address of the investor that needs to be removed
*/
function _removeWhitelisted(address account)
internal
onlyValidAddress(account)
{
require(_isWhitelisted[account] == true, "account was not whitelisted");
_isWhitelisted[account] = false;
emit RemovedWhitelisted(account);
}
}
// File: contracts/crowdsale/WhitelistCrowdsale.sol
/**
* @title Crowdsale with whitelists
* @dev The WhitelistCrowdsale was not included in OZ's release at the moment of the
* development of this contract. Therefore, we've developed the Whitelist contract and
* the WhitelistCrowdsale contract.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
/**
* @title WhitelistCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistCrowdsale is Whitelist, Crowdsale {
/**
* @notice Extend parent behavior requiring beneficiary to be whitelisted.
* @dev Note that no restriction is imposed on the account sending the transaction.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)
internal
view
{
require(isWhitelisted(_beneficiary), "beneficiary is not whitelisted");
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/crowdsale/NonEthPurchasableCrowdsale.sol
/**
* @title Crowdsale that allows to be purchased with fiat
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract NonEthPurchasableCrowdsale is Crowdsale {
event NonEthTokenPurchased(address indexed beneficiary, uint256 tokenAmount);
/**
* @notice Allows onlyManager to mint token for beneficiary.
* @param beneficiary Recipient of the token purchase
* @param tokenAmount Amount of token purchased
*/
function nonEthPurchase(address beneficiary, uint256 tokenAmount)
public
{
_preValidatePurchase(beneficiary, tokenAmount);
_processPurchase(beneficiary, tokenAmount);
emit NonEthTokenPurchased(beneficiary, tokenAmount);
}
}
// File: contracts/crowdsale/UpdatableRateCrowdsale.sol
/**
* @title Crowdsale with updatable exchange rate
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
// @TODO change the pausable manager to other role or the role to be created ->
// whitelisted admin
contract UpdatableRateCrowdsale is PausableManager, Crowdsale {
using SafeMath for uint256;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
// 1 IVO = 0.3213 USD
uint256 private constant TOKEN_PRICE_USD = 3213;
uint256 private constant TOKEN_PRICE_BASE = 10000;
uint256 private constant FIAT_RATE_BASE = 100;
// This vairable is not goint to override the _rate vairable in OZ's _rate vairable
// because of the scope/visibility, however, we could override the getter function
uint256 private _rate;
// USD to ETH rate, as shown on CoinMarketCap.com
// _rate = _fiatRate / ((1 - discount) * (TOKEN_PRICE_USD / TOKEN_PRICE_BASE))
// e.g. If 1 ETH = 110.24 USD, _fiatRate is 11024.
uint256 private _fiatRate;
/**
* Event for fiat to ETH rate update
* @param value the fiatrate
* @param timestamp blocktime of the update
*/
event UpdatedFiatRate (uint256 value, uint256 timestamp);
/**
* @param initialFiatRate The fiat rate (ETH/USD) when crowdsale starts
* @dev 2 decimals. e.g. If 1 ETH = 110.24 USD, _fiatRate is 11024.
*/
constructor (uint256 initialFiatRate) internal {
require(initialFiatRate > 0, "fiat rate is not positive");
_updateRate(initialFiatRate);
}
/**
* @dev Allow manager to update the exchange rate when necessary.
*/
function updateRate(uint256 newFiatRate) external onlyManager {
_updateRate(newFiatRate);
}
/** OVERRIDE
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the ETH price (in USD) currently used in the crowdsale
*/
function fiatRate() public view returns (uint256) {
return _fiatRate;
}
/**
* @notice Calculate the amount of token to be sold based on the amount of wei
* @dev To be overriden to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @notice Update the exchange rate when the fiat rate is changed
* @dev Since we round the _rate now into an integer. There is a loss in purchase
* E.g. When ETH is at 110.24$, one could have 343.106 IVO with 1 ETH of net
* contribution (after deducting the KYC/AML fee) in mainsale. However, only 343 IVO
* will be issued, due to the rounding, resulting in a loss of 0.35 $/ETH purchase.
*/
function _updateRate(uint256 newFiatRate) internal {
_fiatRate = newFiatRate;
_rate = _fiatRate.mul(TOKEN_PRICE_BASE).div(TOKEN_PRICE_USD * FIAT_RATE_BASE);
emit UpdatedFiatRate(_fiatRate, block.timestamp);
}
}
// File: contracts/crowdsale/CappedMultiRoundCrowdsale.sol
/**
* @title Multi-round with cap Crowdsale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CappedMultiRoundCrowdsale is UpdatableRateCrowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ROUNDS = 3;
uint256 private constant CAP_ROUND_ONE = 22500000 ether;
uint256 private constant CAP_ROUND_TWO = 37500000 ether;
uint256 private constant CAP_ROUND_THREE = 52500000 ether;
uint256 private constant HARD_CAP = 52500000 ether;
uint256 private constant PRICE_PERCENTAGE_ROUND_ONE = 80;
uint256 private constant PRICE_PERCENTAGE_ROUND_TWO = 90;
uint256 private constant PRICE_PERCENTAGE_ROUND_THREE = 100;
uint256 private constant PRICE_PERCENTAGE_BASE = 100;
uint256 private _currentRoundCap;
uint256 private _mintedByCrowdsale;
uint256 private _currentRound;
uint256[ROUNDS] private _capOfRound;
uint256[ROUNDS] private _pricePercentagePerRound;
address private privateVaultAddress;
address private presaleVaultAddress;
address private reserveVaultAddress;
/**
* Event for multi-round logging
* @param roundNumber number of the current rounnd, starting from 0
* @param timestamp blocktime of the start of the next block
*/
event RoundStarted(uint256 indexed roundNumber, uint256 timestamp);
/**
* Constructor for the capped multi-round crowdsale
* @param startingTime Time when the first round starts
*/
/* solhint-disable */
constructor (uint256 startingTime) internal {
// update the private variable as the round number and the discount percentage is not changed.
_pricePercentagePerRound[0] = PRICE_PERCENTAGE_ROUND_ONE;
_pricePercentagePerRound[1] = PRICE_PERCENTAGE_ROUND_TWO;
_pricePercentagePerRound[2] = PRICE_PERCENTAGE_ROUND_THREE;
// update the milestones
_capOfRound[0] = CAP_ROUND_ONE;
_capOfRound[1] = CAP_ROUND_TWO;
_capOfRound[2] = CAP_ROUND_THREE;
// initiallization
_currentRound;
_currentRoundCap = _capOfRound[_currentRound];
emit RoundStarted(_currentRound, startingTime);
}
/* solhint-enable */
/**
* @notice Modifier to be executed when multi-round is still going on
*/
modifier stillInRounds() {
require(_currentRound < ROUNDS, "Not in rounds");
_;
}
/**
* @notice Check vault addresses are correcly settled.
*/
/* solhint-disable */
modifier vaultAddressesSet() {
require(privateVaultAddress != address(0) && presaleVaultAddress != address(0) && reserveVaultAddress != address(0), "Vaults are not set");
_;
}
/* solhint-enable */
/**
* @return the cap of the crowdsale.
*/
function hardCap() public pure returns(uint256) {
return HARD_CAP;
}
/**
* @return the cap of the current round of crowdsale.
*/
function currentRoundCap() public view returns(uint256) {
return _currentRoundCap;
}
/**
* @return the amount of token issued by the crowdsale.
*/
function mintedByCrowdsale() public view returns(uint256) {
return _mintedByCrowdsale;
}
/**
* @return the total round of crowdsales.
*/
function rounds() public pure returns(uint256) {
return ROUNDS;
}
/**
* @return the index of current round.
*/
function currentRound() public view returns(uint256) {
return _currentRound;
}
/**
* @return the cap of one round (relative value)
*/
function capOfRound(uint256 index) public view returns(uint256) {
return _capOfRound[index];
}
/**
* @return the discounted price of the current round
*/
function pricePercentagePerRound(uint256 index) public view returns(uint256) {
return _pricePercentagePerRound[index];
}
/**
* @notice Checks whether the cap has been reached.
* @dev These two following functions should not be held because the state should be
* reverted, if the condition is met, therefore no more tokens that exceeds the cap
* shall be minted.
* @return Whether the cap was reached
*/
function hardCapReached() public view returns (bool) {
return _mintedByCrowdsale >= HARD_CAP;
}
/**
* @notice Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function currentRoundCapReached() public view returns (bool) {
return _mintedByCrowdsale >= _currentRoundCap;
}
/**
* @notice Allows manager to manually close the round
*/
function closeCurrentRound() public onlyManager stillInRounds {
_capOfRound[_currentRound] = _mintedByCrowdsale;
_updateRoundCaps(_currentRound);
}
/**
* @dev Extend parent behavior requiring the crowdsale is in a valid round
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
stillInRounds
{
super._preValidatePurchase(beneficiary, weiAmount);
}
/**
* @notice Extend parent behavior requiring purchase to respect the max
* token cap for crowdsale.
* @dev If the transaction is about to exceed the hardcap, the crowdsale contract
* will revert the entire transaction, because the contract will not refund any part
* of msg.value
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Check if the hard cap (in IVO) is reached
// This requirement is actually controlled when calculating the tokenAmount
// inside _dealWithBigTokenPurchase(). So comment the following ou at the moment
// require(_mintedByCrowdsale.add(tokenAmount) <= HARD_CAP, "Too many tokens that exceeds the cap");
// After calculating the generated amount, now update the current round.
// The following block is to process a purchase with amouts that exceeds the current cap.
uint256 finalAmount = _mintedByCrowdsale.add(tokenAmount);
uint256 totalMintedAmount = _mintedByCrowdsale;
for (uint256 i = _currentRound; i < ROUNDS; i = i.add(1)) {
if (finalAmount > _capOfRound[i]) {
sendToCorrectAddress(beneficiary, _capOfRound[i].sub(totalMintedAmount), _currentRound);
// the rest needs to be dealt in the next round.
totalMintedAmount = _capOfRound[i];
_updateRoundCaps(_currentRound);
} else {
_mintedByCrowdsale = finalAmount;
sendToCorrectAddress(beneficiary, finalAmount.sub(totalMintedAmount), _currentRound);
if (finalAmount == _capOfRound[i]) {
_updateRoundCaps(_currentRound);
}
break;
}
}
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* It tokens "discount" into consideration as well as multi-rounds.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
// Here we need to check if all tokens are sold in the same round.
uint256 tokenAmountBeforeDiscount = super._getTokenAmount(weiAmount);
uint256 tokenAmountForThisRound;
uint256 tokenAmountForNextRound;
uint256 tokenAmount;
for (uint256 round = _currentRound; round < ROUNDS; round = round.add(1)) {
(tokenAmountForThisRound, tokenAmountForNextRound) =
_dealWithBigTokenPurchase(tokenAmountBeforeDiscount, round);
tokenAmount = tokenAmount.add(tokenAmountForThisRound);
if (tokenAmountForNextRound == 0) {
break;
} else {
tokenAmountBeforeDiscount = tokenAmountForNextRound;
}
}
// After three rounds of calculation, there should be no more token to be
// purchased in the "next" round. Otherwise, it reaches the hardcap.
require(tokenAmountForNextRound == 0, "there is still tokens for the next round...");
return tokenAmount;
}
/**
* @dev Set up addresses for vaults. Should only be called once during.
* @param privateVault The vault address for private sale
* @param presaleVault The vault address for presale.
* @param reserveVault The vault address for reserve.
*/
function _setVaults(
IVault privateVault,
IVault presaleVault,
IVault reserveVault
)
internal
{
require(address(privateVault) != address(0), "Not valid address: privateVault");
require(address(presaleVault) != address(0), "Not valid address: presaleVault");
require(address(reserveVault) != address(0), "Not valid address: reserveVault");
privateVaultAddress = address(privateVault);
presaleVaultAddress = address(presaleVault);
reserveVaultAddress = address(reserveVault);
}
/**
* @dev When a big token purchase happens, it automatically jumps to the next round if
* the cap of the current round reaches.
* @param tokenAmount The amount of tokens that is converted from wei according to the
* updatable fiat rate. This amount has not yet taken the discount rate into account.
* @return The amount of token sold in this round
* @return The amount of token ready to be sold in the next round.
*/
function _dealWithBigTokenPurchase(uint256 tokenAmount, uint256 round)
private
view
stillInRounds
returns (uint256, uint256)
{
// Get the maximum "tokenAmount" that can be issued in the current around with the
// corresponding discount.
// maxAmount = (absolut cap of the current round - already issued) * discount
uint256 maxTokenAmountOfCurrentRound = (_capOfRound[round]
.sub(_mintedByCrowdsale))
.mul(_pricePercentagePerRound[round])
.div(PRICE_PERCENTAGE_BASE);
if (tokenAmount < maxTokenAmountOfCurrentRound) {
// this purchase will be settled entirely in the current round
return (tokenAmount.mul(PRICE_PERCENTAGE_BASE).div(_pricePercentagePerRound[round]), 0);
} else {
// need to consider cascading to the next round
uint256 tokenAmountOfNextRound = tokenAmount.sub(maxTokenAmountOfCurrentRound);
return (maxTokenAmountOfCurrentRound, tokenAmountOfNextRound);
}
}
/**
* @dev this function delivers token according to the information of the current round...
* @param beneficiary The address of the account that should receive tokens in reality
* @param tokenAmountToBeSent The amount of token sent to the destination addression.
* @param roundNumber Round number where tokens shall be purchased...
*/
function sendToCorrectAddress(
address beneficiary,
uint256 tokenAmountToBeSent,
uint256 roundNumber
)
private
vaultAddressesSet
{
if (roundNumber == 2) {
// then tokens could be minted directly to holder's account
// the amount shall be the
super._processPurchase(beneficiary, tokenAmountToBeSent);
} else if (roundNumber == 0) {
// tokens should be minted to the private sale vault...
super._processPurchase(privateVaultAddress, tokenAmountToBeSent);
// update the balance of the corresponding vault
IVault(privateVaultAddress).receiveFor(beneficiary, tokenAmountToBeSent);
} else {
// _currentRound == 1, tokens should be minted to the presale vault
super._processPurchase(presaleVaultAddress, tokenAmountToBeSent);
// update the balance of the corresponding vault
IVault(presaleVaultAddress).receiveFor(beneficiary, tokenAmountToBeSent);
}
}
/**
* @notice Eachtime, when a manager closes a round or a round_cap is reached, it needs
* to update the info of the _currentRound, _currentRoundCap, _hardCap and _capPerRound[];
* @param round currentRound number
* @dev This function should only be triggered when there is a need of updating all
* the params. The capPerRound shall be updated with the current mintedValue.
*/
function _updateRoundCaps(uint256 round) private {
if (round == 0) {
// update the releasing time of private sale vault
IVault(privateVaultAddress).updateReleaseTime(block.timestamp);
_currentRound = 1;
_currentRoundCap = _capOfRound[1];
} else if (round == 1) {
// update the releasing time of presale vault
IVault(presaleVaultAddress).updateReleaseTime(block.timestamp);
_currentRound = 2;
_currentRoundCap = _capOfRound[2];
} else {
// when _currentRound == 2
IVault(reserveVaultAddress).updateReleaseTime(block.timestamp);
// finalize the crowdsale
_currentRound = 3;
_currentRoundCap = _capOfRound[2];
}
emit RoundStarted(_currentRound, block.timestamp);
}
}
// File: contracts/crowdsale/PausableCrowdsale.sol
/**
* @title Crowdsale with check on pausible
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* This contract is similar to OpenZeppelin's PausableCrowdsale, yet with different
* contract inherited
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableCrowdsale is PausableManager, Crowdsale {
/**
* @notice Validation of an incoming purchase.
* @dev Use require statements to revert state when conditions are not met. Adding
* the validation that the crowdsale must not be paused.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
view
whenNotPaused
{
return super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/crowdsale/StartingTimedCrowdsale.sol
/**
* @title Crowdsale with a limited opening time
* @dev This contract is developed based on OpenZeppelin's TimedCrowdsale contract
* but removing the endTime. As the function `hasEnded()` is public accessible and
* necessary to return true when the crowdsale is ready to be finalized, yet no direct
* link exists between the time and the end, here we take OZ's originalCrowdsale contract
* and tweak according to the need.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract StartingTimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _startingTime;
/**
* @notice Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isStarted(), "Not yet started");
_;
}
/**
* @notice Constructor, takes crowdsale opening and closing times.
* @param startingTime Crowdsale opening time
*/
constructor(uint256 startingTime) internal {
// solium-disable-next-line security/no-block-members
require(startingTime >= block.timestamp, "Starting time is in the past");
_startingTime = startingTime;
}
/**
* @return the crowdsale opening time.
*/
function startingTime() public view returns(uint256) {
return _startingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isStarted() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _startingTime;
}
/**
* @notice Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
view
{
super._preValidatePurchase(beneficiary, weiAmount);
}
}
// File: contracts/crowdsale/FinalizableCrowdsale.sol
/**
* @title Finalizable crowdsale
* @dev This contract is developed based on OpenZeppelin's FinalizableCrowdsale contract
* with a different inherited contract.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
/**
* @title FinalizableCrowdsale
* @notice Extension of Crowdsale with a one-off finalization action, where one
* can do extra work after finishing.
* @dev Slightly different from OZ;s contract, due to the inherited "TimedCrowdsale"
* contract
*/
contract FinalizableCrowdsale is StartingTimedCrowdsale {
using SafeMath for uint256;
bool private _finalized;
event CrowdsaleFinalized(address indexed account);
constructor () internal {
_finalized = false;
}
/**
* @return true if the crowdsale is finalized, false otherwise.
*/
function finalized() public view returns (bool) {
return _finalized;
}
/**
* @notice Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
* @dev The requirement of endingTimeis removed
*/
function finalize() public {
require(!_finalized, "already finalized");
_finalized = true;
emit CrowdsaleFinalized(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an `Approval` event is emitted on calls to `transferFrom`.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard `decreaseAllowance` and `increaseAllowance`
* functions have been added to mitigate the well-known issues around setting
* allowances. See `IERC20.approve`.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol
pragma solidity ^0.5.0;
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount),
"MintedCrowdsale: minting failed"
);
}
}
// File: contracts/crowdsale/IvoCrowdsale.sol
/**
* @title INVAO Crowdsale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IvoCrowdsale is IIvoCrowdsale, CounterGuard, Reclaimable, MintedCrowdsale,
NonEthPurchasableCrowdsale, CappedMultiRoundCrowdsale, WhitelistCrowdsale,
PausableCrowdsale, FinalizableCrowdsale {
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ROUNDS = 3;
uint256 private constant KYC_AML_RATE_DEDUCTED = 965;
uint256 private constant KYC_AML_FEE_BASE = 1000;
bool private _setRole;
/**
* @param startingTime The starting time of the crowdsale
* @param rate Token per wei. This rate is going to be overriden, hence not important.
* @param initialFiatRate USD per ETH. (As the number on CoinMarketCap.com)
* Value written in cent.
* @param wallet The address of the team which receives investors ETH payment.
* @param token The address of the token.
*/
/* solhint-disable */
constructor(
uint256 startingTime,
uint256 rate,
uint256 initialFiatRate,
address payable wallet,
IERC20 token
)
public
Crowdsale(rate, wallet, token)
UpdatableRateCrowdsale(initialFiatRate)
CappedMultiRoundCrowdsale(startingTime)
StartingTimedCrowdsale(startingTime) {}
/* solhint-enable */
/**
* @notice Batch minting tokens for investors paid with non-ETH
* @param beneficiaries Recipients of the token purchase
* @param amounts Amounts of token purchased
*/
function nonEthPurchases(
address[] calldata beneficiaries,
uint256[] calldata amounts
)
external
onlyManager
{
uint256 length = amounts.length;
require(beneficiaries.length == length, "length !=");
require(length <= 256, "To long, please consider shorten the array");
for (uint256 i = 0; i < length; i++) {
super.nonEthPurchase(beneficiaries[i], amounts[i]);
}
}
/** OVERRIDE
* @notice Allows onlyManager to mint token for beneficiaries.
* @param beneficiary Recipient of the token purchase
* @param tokenAmount Amount of token purchased
*/
function nonEthPurchase(address beneficiary, uint256 tokenAmount)
public
onlyManager
{
super.nonEthPurchase(beneficiary, tokenAmount);
}
/**
* @notice Allows manager to manually close the round
*/
function closeCurrentRound() public onlyWhileOpen {
super.closeCurrentRound();
}
/**
* @notice setup roles and contract addresses for the crowdsale contract
* @dev This function can only be called once by the owner.
* @param newOwner The address of the new owner/manager.
* @param privateVault The address of private sale vault
* @param presaleVault The address of presale vault.
* @param reserveVault The address of reverve vault.
*/
function roleSetup(
address newOwner,
IVault privateVault,
IVault presaleVault,
IVault reserveVault
)
public
onlyOwner
onlyOnce(_setRole)
{
_setVaults(privateVault, presaleVault, reserveVault);
addManager(newOwner);
_removeManager(msg.sender);
transferOwnership(newOwner);
_setRole = true;
}
/** OVERRIDE
* @notice Specify the actions in the finalization of the crowdsale.
* Add the manager as a token minter and renounce itself the minter role
* role of the token contract.
*/
function finalize() public onlyManager {
require(this.currentRound() == ROUNDS, "Multi-rounds has not yet completed");
super.finalize();
PausableManager(address(token())).unpause();
ERC20Mintable(address(token())).addMinter(msg.sender);
ERC20Mintable(address(token())).renounceMinter();
}
/*** INTERNAL/PRIVATE ***/
/** OVERRIDE
* @notice Calculate the usable wei after taking out the KYC/AML fee, i.e. 96.5 %
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased after deducting the AML/KYC fee.
*/
function _getTokenAmount(uint256 weiAmount)
internal
view
returns (uint256)
{
uint256 availableWei = weiAmount.mul(KYC_AML_RATE_DEDUCTED).div(KYC_AML_FEE_BASE);
return super._getTokenAmount(availableWei);
}
} | Checks whether the cap has been reached. These two following functions should not be held because the state should be reverted, if the condition is met, therefore no more tokens that exceeds the cap shall be minted. return Whether the cap was reached/ | function hardCapReached() public view returns (bool) {
return _mintedByCrowdsale >= HARD_CAP;
}
| 1,016,765 |
./full_match/1/0x95E3498d96Eb3488f520975B6E191685cAe76Fb7/sources/contracts/P2PEscrow.sol | executes a limit order see executeOrder comments. this function is just a wrapper on top of executeOrder tokenId id of the token that user wants to trade in tokenAmount amount of token user wants to trade in swapTokenId id of the token that a user wants to trade out swapTokenAmount amount of token user wants to trade out timeoutTime expiry time of the order orderId unique order id/ | function limitOrder(
uint16 tokenId,
uint96 tokenAmount,
uint16 swapTokenId,
uint96 swapTokenAmount,
uint32 timeoutTime,
bytes16 orderId
) external returns (bytes16) {
return
executeOrder(
tokenId,
tokenAmount,
swapTokenId,
swapTokenAmount,
timeoutTime,
orderId,
OrderType.LIMIT_ORDER
);
}
| 3,856,523 |
./full_match/1/0x6c51041A91C91C86f3F08a72cB4D3F67f1208897/sources/src/base/Cellar.sol | Withdraw from positions in the order defined by `positions`. assets the amount of assets to withdraw from cellar receiver the address to sent withdrawn assets to Only loop through credit array because debt can not be withdraw by users./ Save asset price in USD, and decimals to reduce external calls. Move on to next position if this one is empty. Convert assets into position asset. | function _withdrawInOrder(uint256 assets, address receiver) internal {
WithdrawPricing memory pricingInfo;
pricingInfo.priceQuoteUSD = priceRouter.getPriceInUSD(asset);
pricingInfo.oneQuote = 10 ** decimals;
uint256 creditLength = creditPositions.length;
for (uint256 i; i < creditLength; ++i) {
uint32 position = creditPositions[i];
uint256 withdrawableBalance = _withdrawableFrom(position);
if (withdrawableBalance == 0) continue;
ERC20 positionAsset = _assetOf(position);
pricingInfo.priceBaseUSD = priceRouter.getPriceInUSD(positionAsset);
pricingInfo.oneBase = 10 ** positionAsset.decimals();
uint256 totalWithdrawableBalanceInAssets;
{
uint256 withdrawableBalanceInUSD = (PRECISION_MULTIPLIER * withdrawableBalance).mulDivDown(
pricingInfo.priceBaseUSD,
pricingInfo.oneBase
);
totalWithdrawableBalanceInAssets = withdrawableBalanceInUSD.mulDivDown(
pricingInfo.oneQuote,
pricingInfo.priceQuoteUSD
);
totalWithdrawableBalanceInAssets = totalWithdrawableBalanceInAssets / PRECISION_MULTIPLIER;
}
if (totalWithdrawableBalanceInAssets > assets) {
uint256 assetsInUSD = (PRECISION_MULTIPLIER * assets).mulDivDown(
pricingInfo.priceQuoteUSD,
pricingInfo.oneQuote
);
amount = assetsInUSD.mulDivDown(pricingInfo.oneBase, pricingInfo.priceBaseUSD);
amount = amount / PRECISION_MULTIPLIER;
assets = 0;
amount = withdrawableBalance;
assets = assets - totalWithdrawableBalanceInAssets;
}
}
}
| 5,008,843 |
./full_match/1/0x0000000304aAD016bA7a745da3cE64f6198B76B3/sources/src/Platform.sol | Set the recipient for a given address. _for Address to set the recipient for. _recipient Address of the recipient. | function setRecipientFor(address _for, address _recipient) external onlyOwner {
recipient[_for] = _recipient;
emit RecipientSet(_for, _recipient);
}
| 3,200,454 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IAccessControlUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), 'AccessControl: can only renounce roles for self');
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
/**
* @title SP1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contracts with storage.
*/
abstract contract SP1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Modifiers ============
/**
* @dev Modifier to ensure the STARK key is allowed.
*/
modifier onlyAllowedKey(
uint256 starkKey
) {
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Storage: STARK key is not on the allowlist');
_;
}
/**
* @dev Modifier to ensure the recipient is allowed.
*/
modifier onlyAllowedRecipient(
address recipient
) {
require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Storage: Recipient is not on the allowlist');
_;
}
// ============ Storage ============
mapping(uint256 => bool) internal _ALLOWED_STARK_KEYS_;
mapping(address => bool) internal _ALLOWED_RECIPIENTS_;
/// @dev Note that withdrawals are always permitted if the amount is in excess of the borrowed
/// amount. Also, this approval only applies to the primary ERC20 token, `TOKEN`.
uint256 internal _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
/// @dev Note that this is different from _IS_BORROWING_RESTRICTED_ in LiquidityStakingV1.
bool internal _IS_BORROWING_RESTRICTED_;
/// @dev Mapping from args hash to timestamp.
mapping(bytes32 => uint256) internal _QUEUED_FORCED_TRADE_TIMESTAMPS_;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @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.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Getters
* @author dYdX
*
* @dev Simple external getter functions.
*/
abstract contract SP1Getters is
SP1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Check whether a STARK key is on the allowlist for exchange operations.
*
* @param starkKey The STARK key to check.
*
* @return Boolean `true` if the STARK key is allowed, otherwise `false`.
*/
function isStarkKeyAllowed(
uint256 starkKey
)
external
view
returns (bool)
{
return _ALLOWED_STARK_KEYS_[starkKey];
}
/**
* @notice Check whether a recipient is on the allowlist to receive withdrawals.
*
* @param recipient The recipient to check.
*
* @return Boolean `true` if the recipient is allowed, otherwise `false`.
*/
function isRecipientAllowed(
address recipient
)
external
view
returns (bool)
{
return _ALLOWED_RECIPIENTS_[recipient];
}
/**
* @notice Get the amount approved by the guardian for external withdrawals.
* Note that withdrawals are always permitted if the amount is in excess of the borrowed amount.
*
* @return The amount approved for external withdrawals.
*/
function getApprovedAmountForExternalWithdrawal()
external
view
returns (uint256)
{
return _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
}
/**
* @notice Check whether this borrower contract is restricted from new borrowing, as well as
* restricted from depositing borrowed funds to the exchange.
*
* @return Boolean `true` if the borrower is restricted, otherwise `false`.
*/
function isBorrowingRestricted()
external
view
returns (bool)
{
return _IS_BORROWING_RESTRICTED_;
}
/**
* @notice Get the timestamp at which a forced trade request was queued.
*
* @param argsHash The hash of the forced trade request args.
*
* @return Timestamp at which the forced trade was queued, or zero, if it was not queued or was
* vetoed by the VETO_GUARDIAN_ROLE.
*/
function getQueuedForcedTradeTimestamp(
bytes32 argsHash
)
external
view
returns (uint256)
{
return _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../interfaces/ILiquidityStakingV1.sol';
import { IMerkleDistributorV1 } from '../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../interfaces/IStarkPerpetual.sol';
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { SP1Withdrawals } from './impl/SP1Withdrawals.sol';
import { SP1Getters } from './impl/SP1Getters.sol';
import { SP1Guardian } from './impl/SP1Guardian.sol';
import { SP1Owner } from './impl/SP1Owner.sol';
/**
* @title StarkProxyV1
* @author dYdX
*
* @notice Proxy contract allowing a LiquidityStaking borrower to use borrowed funds (as well as
* their own funds, if desired) on the dYdX L2 exchange. Restrictions are put in place to
* prevent borrowed funds being used outside the exchange. Furthermore, a guardian address is
* specified which has the ability to restrict borrows and make repayments.
*
* Owner actions may be delegated to various roles as defined in SP1Roles. Other actions are
* available to guardian roles, to be nominated by dYdX governance.
*/
contract StarkProxyV1 is
SP1Guardian,
SP1Owner,
SP1Withdrawals,
SP1Getters
{
using SafeERC20 for IERC20;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token,
IMerkleDistributorV1 merkleDistributor
)
SP1Guardian(liquidityStaking, starkPerpetual, token)
SP1Withdrawals(merkleDistributor)
{}
// ============ External Functions ============
function initialize(address guardian)
external
initializer
{
__SP1Roles_init(guardian);
TOKEN.safeApprove(address(LIQUIDITY_STAKING), uint256(-1));
TOKEN.safeApprove(address(STARK_PERPETUAL), uint256(-1));
}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ILiquidityStakingV1
* @author dYdX
*
* @notice Partial interface for LiquidityStakingV1.
*/
interface ILiquidityStakingV1 {
function getToken() external view virtual returns (address);
function getBorrowedBalance(address borrower) external view virtual returns (uint256);
function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256);
function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool);
function getTimeRemainingInEpoch() external view virtual returns (uint256);
function inBlackoutWindow() external view virtual returns (bool);
// LS1Borrowing
function borrow(uint256 amount) external virtual;
function repayBorrow(address borrower, uint256 amount) external virtual;
function getAllocatedBalanceCurrentEpoch(address borrower)
external
view
virtual
returns (uint256);
function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256);
function getBorrowableAmount(address borrower) external view virtual returns (uint256);
// LS1DebtAccounting
function repayDebt(address borrower, uint256 amount) external virtual;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IMerkleDistributorV1
* @author dYdX
*
* @notice Partial interface for the MerkleDistributorV1 contract.
*/
interface IMerkleDistributorV1 {
function getIpnsName()
external
virtual
view
returns (string memory);
function getRewardsParameters()
external
virtual
view
returns (uint256, uint256, uint256);
function getActiveRoot()
external
virtual
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid);
function getNextRootEpoch()
external
virtual
view
returns (uint256);
function claimRewards(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IStarkPerpetual
* @author dYdX
*
* @notice Partial interface for the StarkPerpetual contract, for accessing the dYdX L2 exchange.
* @dev See https://github.com/starkware-libs/starkex-contracts
*/
interface IStarkPerpetual {
function registerUser(
address ethKey,
uint256 starkKey,
bytes calldata signature
) external;
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
) external;
function withdraw(uint256 starkKey, uint256 assetType) external;
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
) external;
function forcedTradeRequest(
uint256 starkKeyA,
uint256 starkKeyB,
uint256 vaultIdA,
uint256 vaultIdB,
uint256 collateralAssetId,
uint256 syntheticAssetId,
uint256 amountCollateral,
uint256 amountSynthetic,
bool aIsBuyingSynthetic,
uint256 submissionExpirationTime,
uint256 nonce,
bytes calldata signature,
bool premiumCost
) external;
function mainAcceptGovernance() external;
function proxyAcceptGovernance() external;
function mainRemoveGovernor(address governorForRemoval) external;
function proxyRemoveGovernor(address governorForRemoval) external;
function registerAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function applyAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function registerGlobalConfigurationChange(bytes32 configHash) external;
function applyGlobalConfigurationChange(bytes32 configHash) external;
function getEthKey(uint256 starkKey) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IMerkleDistributorV1 } from '../../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Exchange } from './SP1Exchange.sol';
/**
* @title SP1Withdrawals
* @author dYdX
*
* @dev Actions which may be called only by WITHDRAWAL_OPERATOR_ROLE. Allows for withdrawing
* funds from the contract to external addresses that were approved by OWNER_ROLE.
*/
abstract contract SP1Withdrawals is
SP1Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
IMerkleDistributorV1 public immutable MERKLE_DISTRIBUTOR;
// ============ Events ============
event ExternalWithdrewToken(
address recipient,
uint256 amount
);
event ExternalWithdrewOtherToken(
address token,
address recipient,
uint256 amount
);
event ExternalWithdrewEther(
address recipient,
uint256 amount
);
// ============ Constructor ============
constructor(
IMerkleDistributorV1 merkleDistributor
) {
MERKLE_DISTRIBUTOR = merkleDistributor;
}
// ============ External Functions ============
/**
* @notice Claim rewards from the Merkle distributor. They will be held in this contract until
* withdrawn by the WITHDRAWAL_OPERATOR_ROLE.
*
* @param cumulativeAmount The total all-time rewards this contract has earned.
* @param merkleProof The Merkle proof for this contract address and cumulative amount.
*
* @return The amount of new reward received.
*/
function claimRewardsFromMerkleDistributor(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
returns (uint256)
{
return MERKLE_DISTRIBUTOR.claimRewards(cumulativeAmount, merkleProof);
}
/**
* @notice Withdraw a token amount in excess of the borrowed balance, or an amount approved by
* the GUARDIAN_ROLE.
*
* The contract may hold an excess balance if, for example, additional funds were added by the
* contract owner for use with the same exchange account, or if profits were earned from
* activity on the exchange.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawToken(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
// If we are approved for the full amount, then skip the borrowed balance check.
uint256 approvedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
if (approvedAmount >= amount) {
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = approvedAmount.sub(amount);
} else {
uint256 owedBalance = getBorrowedAndDebtBalance();
uint256 tokenBalance = getTokenBalance();
require(tokenBalance > owedBalance, 'SP1Withdrawals: No withdrawable balance');
uint256 availableBalance = tokenBalance.sub(owedBalance);
require(amount <= availableBalance, 'SP1Withdrawals: Amount exceeds withdrawable balance');
// Always decrease the approval amount.
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
}
TOKEN.safeTransfer(recipient, amount);
emit ExternalWithdrewToken(recipient, amount);
}
/**
* @notice Withdraw any ERC20 token balance other than the token used for borrowing.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawOtherToken(
address token,
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
require(
token != address(TOKEN),
'SP1Withdrawals: Cannot use this function to withdraw borrowed token'
);
IERC20(token).safeTransfer(recipient, amount);
emit ExternalWithdrewOtherToken(token, recipient, amount);
}
/**
* @notice Withdraw any ether.
*
* Note: The contract is not expected to hold Ether so this is not normally needed.
*
* @param recipient The recipient to receive Ether. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawEther(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
payable(recipient).transfer(amount);
emit ExternalWithdrewEther(recipient, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from './SP1Borrowing.sol';
import { SP1Exchange } from './SP1Exchange.sol';
/**
* @title SP1Guardian
* @author dYdX
*
* @dev Defines guardian powers, to be owned or delegated by dYdX governance.
*/
abstract contract SP1Guardian is
SP1Borrowing,
SP1Exchange
{
using SafeMath for uint256;
// ============ Events ============
event BorrowingRestrictionChanged(
bool isBorrowingRestricted
);
event GuardianVetoedForcedTradeRequest(
bytes32 argsHash
);
event GuardianUpdateApprovedAmountForExternalWithdrawal(
uint256 amount
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token
)
SP1Borrowing(liquidityStaking, token)
SP1Exchange(starkPerpetual)
{}
// ============ External Functions ============
/**
* @notice Approve an additional amount for external withdrawal by WITHDRAWAL_OPERATOR_ROLE.
*
* @param amount The additional amount to approve for external withdrawal.
*
* @return The new amount approved for external withdrawal.
*/
function increaseApprovedAmountForExternalWithdrawal(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 newApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_.add(
amount
);
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = newApprovedAmount;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(newApprovedAmount);
return newApprovedAmount;
}
/**
* @notice Set the approved amount for external withdrawal to zero.
*
* @return The amount that was previously approved for external withdrawal.
*/
function resetApprovedAmountForExternalWithdrawal()
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 previousApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(0);
return previousApprovedAmount;
}
/**
* @notice Guardian method to restrict borrowing or depositing borrowed funds to the exchange.
*/
function guardianSetBorrowingRestriction(
bool isBorrowingRestricted
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_IS_BORROWING_RESTRICTED_ = isBorrowingRestricted;
emit BorrowingRestrictionChanged(isBorrowingRestricted);
}
/**
* @notice Guardian method to repay this contract's borrowed balance, using this contract's funds.
*
* @param amount Amount to repay.
*/
function guardianRepayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayBorrow(amount, true);
}
/**
* @notice Guardian method to repay a debt balance owed by the borrower.
*
* @param amount Amount to repay.
*/
function guardianRepayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayDebt(amount, true);
}
/**
* @notice Guardian method to trigger a withdrawal. This will transfer funds from StarkPerpetual
* to this contract. This requires a (slow) withdrawal from L2 to have been previously processed.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*
* @return The ERC20 token amount received by this contract.
*/
function guardianWithdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, true);
}
/**
* @notice Guardian method to trigger a forced withdrawal request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP1Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedWithdrawalRequest(
starkKey,
vaultId,
quantizedAmount,
premiumCost,
true // isGuardianAction
);
}
/**
* @notice Guardian method to trigger a forced trade request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP1Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedTradeRequest(args, signature, true);
}
/**
* @notice Guardian method to prevent queued forced trade requests from being executed.
*
* May only be called by VETO_GUARDIAN_ROLE.
*
* @param argsHashes An array of hashes for each forced trade request to veto.
*/
function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
{
for (uint256 i = 0; i < argsHashes.length; i++) {
bytes32 argsHash = argsHashes[i];
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
emit GuardianVetoedForcedTradeRequest(argsHash);
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from './SP1Borrowing.sol';
import { SP1Exchange } from './SP1Exchange.sol';
/**
* @title SP1Owner
* @author dYdX
*
* @dev Actions which may be called only by OWNER_ROLE. These include actions with a larger amount
* of control over the funds held by the contract.
*/
abstract contract SP1Owner is
SP1Borrowing,
SP1Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice Time that must elapse before a queued forced trade request can be submitted.
uint256 public constant FORCED_TRADE_WAITING_PERIOD = 7 days;
/// @notice Max time that may elapse after the waiting period before a queued forced trade
/// request expires.
uint256 public constant FORCED_TRADE_GRACE_PERIOD = 7 days;
// ============ Events ============
event UpdatedStarkKey(
uint256 starkKey,
bool isAllowed
);
event UpdatedExternalRecipient(
address recipient,
bool isAllowed
);
event QueuedForcedTradeRequest(
uint256[12] args,
bytes32 argsHash
);
// ============ External Functions ============
/**
* @notice Allow exchange functions to be called for a particular STARK key.
*
* Will revert if the STARK key is not registered to this contract's address on the
* StarkPerpetual contract.
*
* @param starkKey The STARK key to allow.
*/
function allowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// This will revert with 'USER_UNREGISTERED' if the STARK key was not registered.
address ethKey = STARK_PERPETUAL.getEthKey(starkKey);
// Require the STARK key to be registered to this contract before we allow it to be used.
require(ethKey == address(this), 'SP1Owner: STARK key not registered to this contract');
require(!_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already allowed');
_ALLOWED_STARK_KEYS_[starkKey] = true;
emit UpdatedStarkKey(starkKey, true);
}
/**
* @notice Remove a STARK key from the allowed list.
*
* @param starkKey The STARK key to disallow.
*/
function disallowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already disallowed');
_ALLOWED_STARK_KEYS_[starkKey] = false;
emit UpdatedStarkKey(starkKey, false);
}
/**
* @notice Allow withdrawals of excess funds to be made to a particular recipient.
*
* @param recipient The recipient to allow.
*/
function allowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(!_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already allowed');
_ALLOWED_RECIPIENTS_[recipient] = true;
emit UpdatedExternalRecipient(recipient, true);
}
/**
* @notice Remove a recipient from the allowed list.
*
* @param recipient The recipient to disallow.
*/
function disallowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already disallowed');
_ALLOWED_RECIPIENTS_[recipient] = false;
emit UpdatedExternalRecipient(recipient, false);
}
/**
* @notice Set ERC20 token allowance for the exchange contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setExchangeContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(STARK_PERPETUAL), 0);
IERC20(token).safeApprove(address(STARK_PERPETUAL), amount);
}
/**
* @notice Set ERC20 token allowance for the staking contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setStakingContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), 0);
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), amount);
}
/**
* @notice Request a forced withdrawal from the exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The withdrawal amount denominated in the exchange base units.
* @param premiumCost Whether to pay a higher fee for faster inclusion in certain scenarios.
*/
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost, false);
}
/**
* @notice Queue a forced trade request to be submitted after the waiting period.
*
* @param args Arguments for the forced trade request.
*/
function queueForcedTradeRequest(
uint256[12] calldata args
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = block.timestamp;
emit QueuedForcedTradeRequest(args, argsHash);
}
/**
* @notice Submit a forced trade request that was previously queued.
*
* @param args Arguments for the forced trade request.
* @param signature The signature of the counterparty to the trade.
*/
function forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(args[0]) // starkKeyA
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
uint256 timestamp = _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
require(
timestamp != 0,
'SP1Owner: Forced trade not queued or was vetoed'
);
uint256 elapsed = block.timestamp.sub(timestamp);
require(
elapsed >= FORCED_TRADE_WAITING_PERIOD,
'SP1Owner: Waiting period has not elapsed for forced trade'
);
require(
elapsed <= FORCED_TRADE_WAITING_PERIOD.add(FORCED_TRADE_GRACE_PERIOD),
'SP1Owner: Grace period has elapsed for forced trade'
);
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
_forcedTradeRequest(args, signature, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev 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');
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Balances } from './SP1Balances.sol';
/**
* @title SP1Exchange
* @author dYdX
*
* @dev Handles calls to the StarkPerpetual contract, for interacting with the dYdX L2 exchange.
*
* Standard exchange operation is handled by EXCHANGE_OPERATOR_ROLE. The “forced” actions can only
* be called by the OWNER_ROLE or GUARDIAN_ROLE. Some other functions are also callable by
* the GUARDIAN_ROLE.
*
* See SP1Roles, SP1Guardian, SP1Owner, and SP1Withdrawals.
*/
abstract contract SP1Exchange is
SP1Balances
{
using SafeMath for uint256;
// ============ Constants ============
IStarkPerpetual public immutable STARK_PERPETUAL;
// ============ Events ============
event DepositedToExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 starkVaultId,
uint256 tokenAmount
);
event WithdrewFromExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 tokenAmount,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedWithdrawal(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedTrade(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
IStarkPerpetual starkPerpetual
) {
STARK_PERPETUAL = starkPerpetual;
}
// ============ External Functions ============
/**
* @notice Deposit funds to the exchange.
*
* IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units.
* Currently, the exchange collateral is USDC, denominated in ERC20 token units, but
* this could change.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to deposit.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The deposit amount denominated in the exchange base units.
*
* @return The ERC20 token amount spent.
*/
function depositToExchange(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
// Deposit and get the deposited token amount.
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = startingBalance.sub(endingBalance);
// Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing.
if (_IS_BORROWING_RESTRICTED_) {
require(
endingBalance >= getBorrowedAndDebtBalance(),
'SP1Borrowing: Cannot deposit borrowed funds to the exchange while Restricted'
);
}
emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount);
return tokenAmount;
}
/**
* @notice Trigger a withdrawal of account funds held in the exchange contract. This can be
* called after a (slow) withdrawal has already been processed by the L2 exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to withdraw.
*
* @return The ERC20 token amount received by this contract.
*/
function withdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, false);
}
// ============ Internal Functions ============
function _withdrawFromExchange(
uint256 starkKey,
uint256 assetType,
bool isGuardianAction
)
internal
returns (uint256)
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.withdraw(starkKey, assetType);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = endingBalance.sub(startingBalance);
emit WithdrewFromExchange(starkKey, assetType, tokenAmount, isGuardianAction);
return tokenAmount;
}
function _forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost,
bool isGuardianAction
)
internal
{
STARK_PERPETUAL.forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost);
emit RequestedForcedWithdrawal(starkKey, vaultId, isGuardianAction);
}
function _forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature,
bool isGuardianAction
)
internal
{
// Split into two functions to avoid error 'call stack too deep'.
if (args[11] != 0) {
_forcedTradeRequestPremiumCostTrue(args, signature);
} else {
_forcedTradeRequestPremiumCostFalse(args, signature);
}
emit RequestedForcedTrade(
args[0], // starkKeyA
args[2], // vaultIdA
isGuardianAction
);
}
// ============ Private Functions ============
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostTrue(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
true // premiumCost
);
}
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostFalse(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
false // premiumCost
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Roles } from './SP1Roles.sol';
/**
* @title SP1Balances
* @author dYdX
*
* @dev Contains common constants and functions related to token balances.
*/
abstract contract SP1Balances is
SP1Roles
{
using SafeMath for uint256;
// ============ Constants ============
IERC20 public immutable TOKEN;
ILiquidityStakingV1 public immutable LIQUIDITY_STAKING;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
) {
LIQUIDITY_STAKING = liquidityStaking;
TOKEN = token;
}
// ============ Public Functions ============
function getAllocatedBalanceCurrentEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceCurrentEpoch(address(this));
}
function getAllocatedBalanceNextEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceNextEpoch(address(this));
}
function getBorrowableAmount()
public
view
returns (uint256)
{
if (_IS_BORROWING_RESTRICTED_) {
return 0;
}
return LIQUIDITY_STAKING.getBorrowableAmount(address(this));
}
function getBorrowedBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowedBalance(address(this));
}
function getDebtBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowerDebtBalance(address(this));
}
function getBorrowedAndDebtBalance()
public
view
returns (uint256)
{
return getBorrowedBalance().add(getDebtBalance());
}
function getTokenBalance()
public
view
returns (uint256)
{
return TOKEN.balanceOf(address(this));
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Roles
* @author dYdX
*
* @dev Defines roles used in the StarkProxyV1 contract. The hierarchy and powers of each role
* are described below. Not all roles need to be used.
*
* Overview:
*
* During operation of this contract, funds will flow between the following three
* contracts:
*
* LiquidityStaking <> StarkProxy <> StarkPerpetual
*
* Actions which move fund from left to right are called “open” actions, whereas actions which
* move funds from right to left are called “close” actions.
*
* Also note that the “forced” actions (forced trade and forced withdrawal) require special care
* since they directly impact the financial risk of positions held on the exchange.
*
* Roles:
*
* GUARDIAN_ROLE
* | -> May perform “close” actions as defined above, but “forced” actions can only be taken
* | if the borrower has an outstanding debt balance.
* | -> May restrict “open” actions as defined above, except w.r.t. funds in excess of the
* | borrowed balance.
* | -> May approve a token amount to be withdrawn externally by the WITHDRAWAL_OPERATOR_ROLE
* | to an allowed address.
* |
* +-- VETO_GUARDIAN_ROLE
* -> May veto forced trade requests initiated by the owner, during the waiting period.
*
* OWNER_ROLE
* | -> May add or remove allowed recipients who may receive excess funds.
* | -> May add or remove allowed STARK keys for use on the exchange.
* | -> May set ERC20 allowances on the LiquidityStakingV1 and StarkPerpetual contracts.
* | -> May call the “forced” actions: forcedWithdrawalRequest and forcedTradeRequest.
* |
* +-- DELEGATION_ADMIN_ROLE
* |
* +-- BORROWER_ROLE
* | -> May call functions on LiquidityStakingV1: autoPayOrBorrow, borrow, repay,
* | and repayDebt.
* |
* +-- EXCHANGE_OPERATOR_ROLE
* | -> May call functions on StarkPerpetual: depositToExchange and
* | withdrawFromExchange.
* |
* +-- WITHDRAWAL_OPERATOR_ROLE
* -> May withdraw funds in excess of the borrowed balance to an allowed recipient.
*/
abstract contract SP1Roles is
SP1Storage
{
bytes32 public constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE');
bytes32 public constant VETO_GUARDIAN_ROLE = keccak256('VETO_GUARDIAN_ROLE');
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256('DELEGATION_ADMIN_ROLE');
bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE');
bytes32 public constant EXCHANGE_OPERATOR_ROLE = keccak256('EXCHANGE_OPERATOR_ROLE');
bytes32 public constant WITHDRAWAL_OPERATOR_ROLE = keccak256('WITHDRAWAL_OPERATOR_ROLE');
function __SP1Roles_init(
address guardian
)
internal
{
// Assign GUARDIAN_ROLE.
_setupRole(GUARDIAN_ROLE, guardian);
// Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(DELEGATION_ADMIN_ROLE, msg.sender);
// Set admins for all roles. (Don't use the default admin role.)
_setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(VETO_GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(DELEGATION_ADMIN_ROLE, OWNER_ROLE);
_setRoleAdmin(BORROWER_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(EXCHANGE_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(WITHDRAWAL_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Balances } from './SP1Balances.sol';
/**
* @title SP1Borrowing
* @author dYdX
*
* @dev Handles calls to the LiquidityStaking contract to borrow and repay funds.
*/
abstract contract SP1Borrowing is
SP1Balances
{
using SafeMath for uint256;
// ============ Events ============
event Borrowed(
uint256 amount,
uint256 newBorrowedBalance
);
event RepaidBorrow(
uint256 amount,
uint256 newBorrowedBalance,
bool isGuardianAction
);
event RepaidDebt(
uint256 amount,
uint256 newDebtBalance,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
)
SP1Balances(liquidityStaking, token)
{}
// ============ External Functions ============
/**
* @notice Automatically repay or borrow to bring borrowed balance to the next allocated balance.
* Must be called during the blackout window, to ensure allocated balance will not change before
* the start of the next epoch. Reverts if there are insufficient funds to prevent a shortfall.
*
* Can be called with eth_call to view amounts that will be borrowed or repaid.
*
* @return The newly borrowed amount.
* @return The borrow amount repaid.
* @return The debt amount repaid.
*/
function autoPayOrBorrow()
external
nonReentrant
onlyRole(BORROWER_ROLE)
returns (
uint256,
uint256,
uint256
)
{
// Ensure we are in the blackout window.
require(
LIQUIDITY_STAKING.inBlackoutWindow(),
'SP1Borrowing: Auto-pay may only be used during the blackout window'
);
// Get the borrowed balance, next allocated balance, and token balance.
uint256 borrowedBalance = getBorrowedBalance();
uint256 nextAllocatedBalance = getAllocatedBalanceNextEpoch();
uint256 tokenBalance = getTokenBalance();
// Return values.
uint256 borrowAmount = 0;
uint256 repayBorrowAmount = 0;
uint256 repayDebtAmount = 0;
if (borrowedBalance > nextAllocatedBalance) {
// Make the necessary repayment due by the end of the current epoch.
repayBorrowAmount = borrowedBalance.sub(nextAllocatedBalance);
require(
tokenBalance >= repayBorrowAmount,
'SP1Borrowing: Insufficient funds to avoid falling short on repayment'
);
_repayBorrow(repayBorrowAmount, false);
} else {
// Borrow the max borrowable amount.
borrowAmount = getBorrowableAmount();
if (borrowAmount != 0) {
_borrow(borrowAmount);
}
}
// Finally, use remaining funds to pay any overdue debt.
uint256 debtBalance = getDebtBalance();
repayDebtAmount = Math.min(debtBalance, tokenBalance);
if (repayDebtAmount != 0) {
_repayDebt(repayDebtAmount, false);
}
return (borrowAmount, repayBorrowAmount, repayDebtAmount);
}
function borrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
// Disallow if the guardian has restricted borrowing.
require(
!_IS_BORROWING_RESTRICTED_,
'SP1Borrowing: Cannot borrow while Restricted'
);
_borrow(amount);
}
function repayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayBorrow(amount, false);
}
function repayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayDebt(amount, false);
}
// ============ Internal Functions ============
function _borrow(
uint256 amount
)
internal
{
LIQUIDITY_STAKING.borrow(amount);
emit Borrowed(amount, getBorrowedBalance());
}
function _repayBorrow(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayBorrow(address(this), amount);
emit RepaidBorrow(amount, getBorrowedBalance(), isGovernanceAction);
}
function _repayDebt(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayDebt(address(this), amount);
emit RepaidDebt(amount, getDebtBalance(), isGovernanceAction);
}
}
| Guardian method to prevent queued forced trade requests from being executed. May only be called by VETO_GUARDIAN_ROLE. argsHashes An array of hashes for each forced trade request to veto./ | function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
{
for (uint256 i = 0; i < argsHashes.length; i++) {
bytes32 argsHash = argsHashes[i];
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
emit GuardianVetoedForcedTradeRequest(argsHash);
}
}
| 221,863 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.