file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAssetAllocation} from "contracts/common/Imports.sol";
import {CurveLusdConstants} from "./Constants.sol";
import {
MetaPoolDepositorZap
} from "contracts/protocols/curve/metapool/Imports.sol";
contract CurveLusdZap is MetaPoolDepositorZap, CurveLusdConstants {
constructor()
public
MetaPoolDepositorZap(
META_POOL,
address(LP_TOKEN),
address(LIQUIDITY_GAUGE),
10000,
100
) // solhint-disable-next-line no-empty-blocks
{}
function assetAllocations() public view override returns (string[] memory) {
string[] memory allocationNames = new string[](1);
allocationNames[0] = NAME;
return allocationNames;
}
function erc20Allocations() public view override returns (IERC20[] memory) {
IERC20[] memory allocations = _createErc20AllocationArray(1);
allocations[4] = PRIMARY_UNDERLYER;
return allocations;
}
}
// 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: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IDetailedERC20} from "./IDetailedERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {
ReentrancyGuard
} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {AccessControl} from "./AccessControl.sol";
import {INameIdentifier} from "./INameIdentifier.sol";
import {IAssetAllocation} from "./IAssetAllocation.sol";
import {IEmergencyExit} from "./IEmergencyExit.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20, INameIdentifier} from "contracts/common/Imports.sol";
import {
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
import {IMetaPool} from "contracts/protocols/curve/metapool/Imports.sol";
abstract contract CurveLusdConstants is INameIdentifier {
string public constant override NAME = "curve-lusd";
// sometimes a metapool is its own LP token; otherwise,
// you can obtain from `token` attribute
IERC20 public constant LP_TOKEN =
IERC20(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA);
// metapool primary underlyer
IERC20 public constant PRIMARY_UNDERLYER =
IERC20(0x5f98805A4E8be255a32880FDeC7F6728C6568bA0);
ILiquidityGauge public constant LIQUIDITY_GAUGE =
ILiquidityGauge(0x9B8519A9a00100720CCdC8a120fBeD319cA47a14);
IMetaPool public constant META_POOL =
IMetaPool(0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IMetaPool} from "./IMetaPool.sol";
import {IOldDepositor} from "./IOldDepositor.sol";
import {IDepositor} from "./IDepositor.sol";
import {DepositorConstants} from "./Constants.sol";
import {MetaPoolAllocationBase} from "./MetaPoolAllocationBase.sol";
import {MetaPoolOldDepositorZap} from "./MetaPoolOldDepositorZap.sol";
import {MetaPoolDepositorZap} from "./MetaPoolDepositorZap.sol";
// 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: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 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: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.11;
import {
AccessControl as OZAccessControl
} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @notice Extends OpenZeppelin AccessControl contract with modifiers
* @dev This contract and AccessControlUpgradeSafe are essentially duplicates.
*/
contract AccessControl is OZAccessControl {
/** @notice access control roles **/
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
bytes32 public constant LP_ROLE = keccak256("LP_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
modifier onlyLpRole() {
require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE");
_;
}
modifier onlyContractRole() {
require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE");
_;
}
modifier onlyAdminRole() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyEmergencyRole() {
require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE");
_;
}
modifier onlyLpOrContractRole() {
require(
hasRole(LP_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_LP_OR_CONTRACT_ROLE"
);
_;
}
modifier onlyAdminOrContractRole() {
require(
hasRole(ADMIN_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_ADMIN_OR_CONTRACT_ROLE"
);
_;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Used by the `NamedAddressSet` library to store sets of contracts
*/
interface INameIdentifier {
/// @notice Should be implemented as a constant value
// solhint-disable-next-line func-name-mixedcase
function NAME() external view returns (string memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {INameIdentifier} from "./INameIdentifier.sol";
/**
* @notice For use with the `TvlManager` to track the value locked in a protocol
*/
interface IAssetAllocation is INameIdentifier {
struct TokenData {
address token;
string symbol;
uint8 decimals;
}
/**
* @notice Get data for the underlying tokens stored in the protocol
* @return The array of `TokenData`
*/
function tokens() external view returns (TokenData[] memory);
/**
* @notice Get the number of different tokens stored in the protocol
* @return The number of tokens
*/
function numberOfTokens() external view returns (uint256);
/**
* @notice Get an account's balance for a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param account The account to get the balance for
* @param tokenIndex The index of the token to get the balance for
* @return The account's balance
*/
function balanceOf(address account, uint8 tokenIndex)
external
view
returns (uint256);
/**
* @notice Get the symbol of a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param tokenIndex The index of the token
* @return The symbol of the token
*/
function symbolOf(uint8 tokenIndex) external view returns (string memory);
/**
* @notice Get the decimals of a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param tokenIndex The index of the token
* @return The decimals of the token
*/
function decimalsOf(uint8 tokenIndex) external view returns (uint8);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "./Imports.sol";
/**
* @notice Used for contracts that need an emergency escape hatch
* @notice Should only be used in an emergency to keep funds safu
*/
interface IEmergencyExit {
/**
* @param emergencySafe The address the tokens were escaped to
* @param token The token escaped
* @param balance The amount of tokens escaped
*/
event EmergencyExit(address emergencySafe, IERC20 token, uint256 balance);
/**
* @notice Transfer all tokens to the emergency Safe
* @dev Should only be callable by the emergency Safe
* @dev Should only transfer tokens to the emergency Safe
* @param token The token to transfer
*/
function emergencyExit(address token) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/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.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {CTokenInterface} from "./CTokenInterface.sol";
import {ITokenMinter} from "./ITokenMinter.sol";
import {IStableSwap, IStableSwap3} from "./IStableSwap.sol";
import {IStableSwap2} from "./IStableSwap2.sol";
import {IStableSwap4} from "./IStableSwap4.sol";
import {IOldStableSwap2} from "./IOldStableSwap2.sol";
import {IOldStableSwap3} from "./IOldStableSwap3.sol";
import {IOldStableSwap4} from "./IOldStableSwap4.sol";
import {ILiquidityGauge} from "./ILiquidityGauge.sol";
import {IStakingRewards} from "./IStakingRewards.sol";
import {IDepositZap} from "./IDepositZap.sol";
import {IDepositZap3} from "./IDepositZap3.sol";
// SPDX-License-Identifier: BSD 3-Clause
/*
* https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
*/
pragma solidity 0.6.11;
interface CTokenInterface {
function symbol() external returns (string memory);
function decimals() external returns (uint8);
function totalSupply() external returns (uint256);
function isCToken() external returns (bool);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function accrueInterest() external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @notice the Curve token minter
* @author Curve Finance
* @dev translated from vyper
* license MIT
* version 0.2.4
*/
// solhint-disable func-name-mixedcase, func-param-name-mixedcase
interface ITokenMinter {
/**
* @notice Mint everything which belongs to `msg.sender` and send to them
* @param gauge_addr `LiquidityGauge` address to get mintable amount from
*/
function mint(address gauge_addr) external;
/**
* @notice Mint everything which belongs to `msg.sender` across multiple gauges
* @param gauge_addrs List of `LiquidityGauge` addresses
*/
function mint_many(address[8] calldata gauge_addrs) external;
/**
* @notice Mint tokens for `_for`
* @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint`
* @param gauge_addr `LiquidityGauge` address to get mintable amount from
* @param _for Address to mint to
*/
function mint_for(address gauge_addr, address _for) external;
/**
* @notice allow `minting_user` to mint for `msg.sender`
* @param minting_user Address to toggle permission for
*/
function toggle_approve_mint(address minting_user) external;
}
// solhint-enable
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice the stablecoin pool contract
*/
interface IStableSwap {
function balances(uint256 coin) external view returns (uint256);
function coins(uint256 coin) external view returns (address);
// solhint-disable-next-line
function underlying_coins(uint256 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)
external;
// solhint-disable-next-line
function add_liquidity(
uint256[3] memory amounts,
uint256 minMinAmount,
bool useUnderlyer
) external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts)
external;
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 tokenAmount,
int128 tokenIndex,
uint256 minAmount
) external;
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 tokenAmount,
int128 tokenIndex,
uint256 minAmount,
bool useUnderlyer
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
/**
* @dev For newest curve pools like aave; older pools refer to a private `token` variable.
*/
// function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase
}
// solhint-disable-next-line no-empty-blocks
interface IStableSwap3 is IStableSwap {
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the stablecoin pool contract
*/
interface IStableSwap2 {
function balances(uint256 coin) external view returns (uint256);
function coins(uint256 coin) external view returns (address);
// solhint-disable-next-line
function underlying_coins(uint256 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)
external;
// solhint-disable-next-line
function add_liquidity(
uint256[2] memory amounts,
uint256 minMinAmount,
bool useUnderlyer
) external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts)
external;
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 tokenAmount,
int128 tokenIndex,
uint256 minAmount
) external;
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 tokenAmount,
int128 tokenIndex,
uint256 minAmount,
bool useUnderlyer
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
/**
* @dev For newest curve pools like aave; older pools refer to a private `token` variable.
*/
// function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the stablecoin pool contract
*/
interface IStableSwap4 {
function balances(uint256 coin) external view returns (uint256);
function coins(uint256 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount)
external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts)
external;
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 tokenAmount,
int128 tokenIndex,
uint256 minAmount
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
/**
* @dev For newest curve pools like aave; older pools refer to a private `token` variable.
*/
// function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the stablecoin pool contract
*/
interface IOldStableSwap2 {
function balances(int128 coin) external view returns (uint256);
function coins(int128 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)
external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts)
external;
/// @dev need this due to lack of `remove_liquidity_one_coin`
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy // solhint-disable-line func-param-name-mixedcase
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
/**
* @dev For newest curve pools like aave; older pools refer to a private `token` variable.
*/
// function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the stablecoin pool contract
*/
interface IOldStableSwap3 {
function balances(int128 coin) external view returns (uint256);
function coins(int128 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)
external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts)
external;
/// @dev need this due to lack of `remove_liquidity_one_coin`
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy // solhint-disable-line func-param-name-mixedcase
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the stablecoin pool contract
*/
interface IOldStableSwap4 {
function balances(int128 coin) external view returns (uint256);
function coins(int128 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount)
external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts)
external;
/// @dev need this due to lack of `remove_liquidity_one_coin`
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy // solhint-disable-line func-param-name-mixedcase
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the liquidity gauge, i.e. staking contract, for the stablecoin pool
*/
interface ILiquidityGauge {
function deposit(uint256 _value) external;
function deposit(uint256 _value, address _addr) external;
function withdraw(uint256 _value) external;
/**
* @notice Claim available reward tokens for msg.sender
*/
// solhint-disable-next-line func-name-mixedcase
function claim_rewards() external;
/**
* @notice Get the number of claimable reward tokens for a user
* @dev This function should be manually changed to "view" in the ABI
* Calling it via a transaction will claim available reward tokens
* @param _addr Account to get reward amount for
* @param _token Token to get reward amount for
* @return uint256 Claimable reward token amount
*/
// solhint-disable-next-line func-name-mixedcase
function claimable_reward(address _addr, address _token)
external
returns (uint256);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/*
* Synthetix: StakingRewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
*/
interface IStakingRewards {
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-2.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice deposit contract used for pools such as Compound and USDT
*/
interface IDepositZap {
// solhint-disable-next-line
function underlying_coins(int128 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)
external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 _amount,
int128 i,
uint256 minAmount
) external;
function curve() external view returns (address);
}
// SPDX-License-Identifier: BUSDL-2.1
pragma solidity 0.6.11;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice deposit contract used for pools such as Compound and USDT
*/
interface IDepositZap3 {
// solhint-disable-next-line
function underlying_coins(int128 coin) external view returns (address);
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)
external;
/**
* @dev the number of coins is hard-coded in curve contracts
*/
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 _amount,
int128 i,
uint256 minAmount
) external;
function curve() external view returns (address);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @notice the Curve metapool contract
* @dev A metapool is sometimes its own LP token
*/
interface IMetaPool is IERC20 {
/// @dev 1st coin is the protocol token, 2nd is the Curve base pool
function balances(uint256 coin) external view returns (uint256);
/// @dev 1st coin is the protocol token, 2nd is the Curve base pool
function coins(uint256 coin) external view returns (address);
/// @dev the number of coins is hard-coded in curve contracts
// solhint-disable-next-line
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)
external;
/// @dev the number of coins is hard-coded in curve contracts
// solhint-disable-next-line
function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts)
external;
// solhint-disable-next-line
function remove_liquidity_one_coin(
uint256 tokenAmount,
int128 tokenIndex,
uint256 minAmount
) external;
// solhint-disable-next-line
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
interface IOldDepositor {
// solhint-disable
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount)
external
returns (uint256);
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external returns (uint256);
function coins(uint256 i) external view returns (address);
function base_coins(uint256 i) external view returns (address);
// solhint-enable
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
interface IDepositor {
// solhint-disable
function add_liquidity(
address _pool,
uint256[4] calldata _deposit_amounts,
uint256 _min_mint_amount
) external returns (uint256);
// solhint-enable
// solhint-disable
function remove_liquidity_one_coin(
address _pool,
uint256 _burn_amount,
int128 i,
uint256 _min_amounts
) external returns (uint256);
// solhint-enable
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {
IStableSwap
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
import {IDepositor} from "./IDepositor.sol";
abstract contract DepositorConstants {
IStableSwap public constant BASE_POOL =
IStableSwap(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
// A depositor "zap" contract for metapools
IDepositor public constant DEPOSITOR =
IDepositor(0xA79828DF1850E8a3A3064576f380D90aECDD3359);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.11;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
import {IMetaPool} from "./IMetaPool.sol";
import {
Curve3poolAllocation
} from "contracts/protocols/curve/3pool/Allocation.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
Curve3poolUnderlyerConstants
} from "contracts/protocols/curve/3pool/Constants.sol";
/**
* @title Periphery Contract for a Curve metapool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
abstract contract MetaPoolAllocationBase is
ImmutableAssetAllocation,
Curve3poolUnderlyerConstants
{
using SafeMath for uint256;
/// @dev all existing Curve metapools are paired with 3pool
Curve3poolAllocation public immutable curve3poolAllocation;
constructor(address curve3poolAllocation_) public {
curve3poolAllocation = Curve3poolAllocation(curve3poolAllocation_);
}
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param metaPool the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IMetaPool metaPool,
ILiquidityGauge gauge,
IERC20 lpToken,
uint256 coin
) public view returns (uint256 balance) {
require(address(metaPool) != address(0), "INVALID_POOL");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(metaPool, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) =
getLpTokenShare(account, metaPool, gauge, lpToken);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IMetaPool metaPool, uint256 coin)
public
view
returns (uint256)
{
require(address(metaPool) != address(0), "INVALID_POOL");
require(coin < 256, "INVALID_COIN");
if (coin == 0) {
return metaPool.balances(0);
}
coin -= 1;
uint256 balance =
curve3poolAllocation.balanceOf(address(metaPool), uint8(coin));
// renormalize using the pool's tracked 3Crv balance
IERC20 baseLpToken = IERC20(metaPool.coins(1));
uint256 adjustedBalance =
balance.mul(metaPool.balances(1)).div(
baseLpToken.balanceOf(address(metaPool))
);
return adjustedBalance;
}
function getLpTokenShare(
address account,
IMetaPool metaPool,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(metaPool) != address(0), "INVALID_POOL");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
function _getBasePoolTokenData(
address primaryUnderlyer,
string memory symbol,
uint8 decimals
) internal pure returns (TokenData[] memory) {
TokenData[] memory tokens = new TokenData[](4);
tokens[0] = TokenData(primaryUnderlyer, symbol, decimals);
tokens[1] = TokenData(DAI_ADDRESS, "DAI", 18);
tokens[2] = TokenData(USDC_ADDRESS, "USDC", 6);
tokens[3] = TokenData(USDT_ADDRESS, "USDT", 6);
return tokens;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAssetAllocation} from "contracts/common/Imports.sol";
import {IMetaPool} from "./IMetaPool.sol";
import {IOldDepositor} from "./IOldDepositor.sol";
import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol";
abstract contract MetaPoolOldDepositorZap is CurveGaugeZapBase {
IOldDepositor internal immutable _DEPOSITOR;
IMetaPool internal immutable _META_POOL;
constructor(
IOldDepositor depositor,
IMetaPool metapool,
address lpAddress,
address gaugeAddress,
uint256 denominator,
uint256 slippage
)
public
CurveGaugeZapBase(
address(depositor),
lpAddress,
gaugeAddress,
denominator,
slippage,
4
)
{
_DEPOSITOR = depositor;
_META_POOL = metapool;
}
function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)
internal
override
{
_DEPOSITOR.add_liquidity(
[amounts[0], amounts[1], amounts[2], amounts[3]],
minAmount
);
}
function _removeLiquidity(
uint256 lpBalance,
uint8 index,
uint256 minAmount
) internal override {
IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), 0);
IERC20(LP_ADDRESS).safeApprove(address(_DEPOSITOR), lpBalance);
_DEPOSITOR.remove_liquidity_one_coin(lpBalance, index, minAmount);
}
function _getVirtualPrice() internal view override returns (uint256) {
return _META_POOL.get_virtual_price();
}
function _getCoinAtIndex(uint256 i)
internal
view
override
returns (address)
{
if (i == 0) {
return _DEPOSITOR.coins(0);
} else {
return _DEPOSITOR.base_coins(i.sub(1));
}
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAssetAllocation} from "contracts/common/Imports.sol";
import {IMetaPool} from "./IMetaPool.sol";
import {DepositorConstants} from "./Constants.sol";
import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol";
abstract contract MetaPoolDepositorZap is
CurveGaugeZapBase,
DepositorConstants
{
IMetaPool internal immutable _META_POOL;
constructor(
IMetaPool metapool,
address lpAddress,
address gaugeAddress,
uint256 denominator,
uint256 slippage
)
public
CurveGaugeZapBase(
address(DEPOSITOR),
lpAddress,
gaugeAddress,
denominator,
slippage,
4
)
{
_META_POOL = metapool;
}
function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)
internal
override
{
DEPOSITOR.add_liquidity(
address(_META_POOL),
[amounts[0], amounts[1], amounts[2], amounts[3]],
minAmount
);
}
function _removeLiquidity(
uint256 lpBalance,
uint8 index,
uint256 minAmount
) internal override {
IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), 0);
IERC20(LP_ADDRESS).safeApprove(address(DEPOSITOR), lpBalance);
DEPOSITOR.remove_liquidity_one_coin(
address(_META_POOL),
lpBalance,
index,
minAmount
);
}
function _getVirtualPrice() internal view override returns (uint256) {
return _META_POOL.get_virtual_price();
}
function _getCoinAtIndex(uint256 i)
internal
view
override
returns (address)
{
if (i == 0) {
return _META_POOL.coins(0);
} else {
return BASE_POOL.coins(i.sub(1));
}
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {NamedAddressSet} from "./NamedAddressSet.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IERC20} from "contracts/common/Imports.sol";
import {SafeMath} from "contracts/libraries/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
IStableSwap,
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
import {
CurveAllocationBase
} from "contracts/protocols/curve/common/Imports.sol";
import {Curve3poolConstants} from "./Constants.sol";
contract Curve3poolAllocation is
CurveAllocationBase,
ImmutableAssetAllocation,
Curve3poolConstants
{
function balanceOf(address account, uint8 tokenIndex)
public
view
override
returns (uint256)
{
return
super.getUnderlyerBalance(
account,
IStableSwap(STABLE_SWAP_ADDRESS),
ILiquidityGauge(LIQUIDITY_GAUGE_ADDRESS),
IERC20(LP_TOKEN_ADDRESS),
uint256(tokenIndex)
);
}
function _getTokenData()
internal
pure
override
returns (TokenData[] memory)
{
TokenData[] memory tokens = new TokenData[](3);
tokens[0] = TokenData(DAI_ADDRESS, "DAI", 18);
tokens[1] = TokenData(USDC_ADDRESS, "USDC", 6);
tokens[2] = TokenData(USDT_ADDRESS, "USDT", 6);
return tokens;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IErc20Allocation} from "./IErc20Allocation.sol";
import {IChainlinkRegistry} from "./IChainlinkRegistry.sol";
import {IAssetAllocationRegistry} from "./IAssetAllocationRegistry.sol";
import {AssetAllocationBase} from "./AssetAllocationBase.sol";
import {ImmutableAssetAllocation} from "./ImmutableAssetAllocation.sol";
import {Erc20AllocationConstants} from "./Erc20Allocation.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {INameIdentifier} from "contracts/common/Imports.sol";
abstract contract Curve3poolUnderlyerConstants {
// underlyer addresses
address public constant DAI_ADDRESS =
0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC_ADDRESS =
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT_ADDRESS =
0xdAC17F958D2ee523a2206206994597C13D831ec7;
}
abstract contract Curve3poolConstants is
Curve3poolUnderlyerConstants,
INameIdentifier
{
string public constant override NAME = "curve-3pool";
address public constant STABLE_SWAP_ADDRESS =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
address public constant LP_TOKEN_ADDRESS =
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
address public constant LIQUIDITY_GAUGE_ADDRESS =
0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A;
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IAssetAllocation, INameIdentifier} from "contracts/common/Imports.sol";
import {IZap, ISwap} from "contracts/lpaccount/Imports.sol";
/**
* @notice Stores a set of addresses that can be looked up by name
* @notice Addresses can be added or removed dynamically
* @notice Useful for keeping track of unique deployed contracts
* @dev Each address must be a contract with a `NAME` constant for lookup
*/
// solhint-disable ordering
library NamedAddressSet {
using EnumerableSet for EnumerableSet.AddressSet;
struct Set {
EnumerableSet.AddressSet _namedAddresses;
mapping(string => INameIdentifier) _nameLookup;
}
struct AssetAllocationSet {
Set _inner;
}
struct ZapSet {
Set _inner;
}
struct SwapSet {
Set _inner;
}
function _add(Set storage set, INameIdentifier namedAddress) private {
require(Address.isContract(address(namedAddress)), "INVALID_ADDRESS");
require(
!set._namedAddresses.contains(address(namedAddress)),
"DUPLICATE_ADDRESS"
);
string memory name = namedAddress.NAME();
require(bytes(name).length != 0, "INVALID_NAME");
require(address(set._nameLookup[name]) == address(0), "DUPLICATE_NAME");
set._namedAddresses.add(address(namedAddress));
set._nameLookup[name] = namedAddress;
}
function _remove(Set storage set, string memory name) private {
address namedAddress = address(set._nameLookup[name]);
require(namedAddress != address(0), "INVALID_NAME");
set._namedAddresses.remove(namedAddress);
delete set._nameLookup[name];
}
function _contains(Set storage set, INameIdentifier namedAddress)
private
view
returns (bool)
{
return set._namedAddresses.contains(address(namedAddress));
}
function _length(Set storage set) private view returns (uint256) {
return set._namedAddresses.length();
}
function _at(Set storage set, uint256 index)
private
view
returns (INameIdentifier)
{
return INameIdentifier(set._namedAddresses.at(index));
}
function _get(Set storage set, string memory name)
private
view
returns (INameIdentifier)
{
return set._nameLookup[name];
}
function _names(Set storage set) private view returns (string[] memory) {
uint256 length_ = set._namedAddresses.length();
string[] memory names_ = new string[](length_);
for (uint256 i = 0; i < length_; i++) {
INameIdentifier namedAddress =
INameIdentifier(set._namedAddresses.at(i));
names_[i] = namedAddress.NAME();
}
return names_;
}
function add(
AssetAllocationSet storage set,
IAssetAllocation assetAllocation
) internal {
_add(set._inner, assetAllocation);
}
function remove(AssetAllocationSet storage set, string memory name)
internal
{
_remove(set._inner, name);
}
function contains(
AssetAllocationSet storage set,
IAssetAllocation assetAllocation
) internal view returns (bool) {
return _contains(set._inner, assetAllocation);
}
function length(AssetAllocationSet storage set)
internal
view
returns (uint256)
{
return _length(set._inner);
}
function at(AssetAllocationSet storage set, uint256 index)
internal
view
returns (IAssetAllocation)
{
return IAssetAllocation(address(_at(set._inner, index)));
}
function get(AssetAllocationSet storage set, string memory name)
internal
view
returns (IAssetAllocation)
{
return IAssetAllocation(address(_get(set._inner, name)));
}
function names(AssetAllocationSet storage set)
internal
view
returns (string[] memory)
{
return _names(set._inner);
}
function add(ZapSet storage set, IZap zap) internal {
_add(set._inner, zap);
}
function remove(ZapSet storage set, string memory name) internal {
_remove(set._inner, name);
}
function contains(ZapSet storage set, IZap zap)
internal
view
returns (bool)
{
return _contains(set._inner, zap);
}
function length(ZapSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(ZapSet storage set, uint256 index)
internal
view
returns (IZap)
{
return IZap(address(_at(set._inner, index)));
}
function get(ZapSet storage set, string memory name)
internal
view
returns (IZap)
{
return IZap(address(_get(set._inner, name)));
}
function names(ZapSet storage set) internal view returns (string[] memory) {
return _names(set._inner);
}
function add(SwapSet storage set, ISwap swap) internal {
_add(set._inner, swap);
}
function remove(SwapSet storage set, string memory name) internal {
_remove(set._inner, name);
}
function contains(SwapSet storage set, ISwap swap)
internal
view
returns (bool)
{
return _contains(set._inner, swap);
}
function length(SwapSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(SwapSet storage set, uint256 index)
internal
view
returns (ISwap)
{
return ISwap(address(_at(set._inner, index)));
}
function get(SwapSet storage set, string memory name)
internal
view
returns (ISwap)
{
return ISwap(address(_get(set._inner, name)));
}
function names(SwapSet storage set)
internal
view
returns (string[] memory)
{
return _names(set._inner);
}
}
// solhint-enable ordering
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IZap} from "./IZap.sol";
import {ISwap} from "./ISwap.sol";
import {ILpAccount} from "./ILpAccount.sol";
import {IZapRegistry} from "./IZapRegistry.sol";
import {ISwapRegistry} from "./ISwapRegistry.sol";
import {IStableSwap3Pool} from "./IStableSwap3Pool.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
IAssetAllocation,
INameIdentifier,
IERC20
} from "contracts/common/Imports.sol";
/**
* @notice Used to define how an LP Account farms an external protocol
*/
interface IZap is INameIdentifier {
/**
* @notice Deploy liquidity to a protocol (i.e. enter a farm)
* @dev Implementation should add liquidity and stake LP tokens
* @param amounts Amount of each token to deploy
*/
function deployLiquidity(uint256[] calldata amounts) external;
/**
* @notice Unwind liquidity from a protocol (i.e exit a farm)
* @dev Implementation should unstake LP tokens and remove liquidity
* @dev If there is only one token to unwind, `index` should be 0
* @param amount Amount of liquidity to unwind
* @param index Which token should be unwound
*/
function unwindLiquidity(uint256 amount, uint8 index) external;
/**
* @notice Claim accrued rewards from the protocol (i.e. harvest yield)
*/
function claim() external;
/**
* @notice Retrieves the LP token balance
*/
function getLpTokenBalance(address account) external view returns (uint256);
/**
* @notice Order of tokens for deploy `amounts` and unwind `index`
* @dev Implementation should use human readable symbols
* @dev Order should be the same for deploy and unwind
* @return The array of symbols in order
*/
function sortedSymbols() external view returns (string[] memory);
/**
* @notice Asset allocations to include in TVL
* @dev Requires all allocations that track value deployed to the protocol
* @return An array of the asset allocation names
*/
function assetAllocations() external view returns (string[] memory);
/**
* @notice ERC20 asset allocations to include in TVL
* @dev Should return addresses for all tokens that get deployed or unwound
* @return The array of ERC20 token addresses
*/
function erc20Allocations() external view returns (IERC20[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
IAssetAllocation,
INameIdentifier,
IERC20
} from "contracts/common/Imports.sol";
/**
* @notice Used to define a token swap that can be performed by an LP Account
*/
interface ISwap is INameIdentifier {
/**
* @dev Implementation should perform a token swap
* @param amount The amount of the input token to swap
* @param minAmount The minimum amount of the output token to accept
*/
function swap(uint256 amount, uint256 minAmount) external;
/**
* @notice ERC20 asset allocations to include in TVL
* @dev Should return addresses for all tokens going in and out of the swap
* @return The array of ERC20 token addresses
*/
function erc20Allocations() external view returns (IERC20[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice For contracts that provide liquidity to external protocols
*/
interface ILpAccount {
/**
* @notice Deploy liquidity with a registered `IZap`
* @dev The order of token amounts should match `IZap.sortedSymbols`
* @param name The name of the `IZap`
* @param amounts The token amounts to deploy
*/
function deployStrategy(string calldata name, uint256[] calldata amounts)
external;
/**
* @notice Unwind liquidity with a registered `IZap`
* @dev The index should match the order of `IZap.sortedSymbols`
* @param name The name of the `IZap`
* @param amount The amount of the token to unwind
* @param index The index of the token to unwind into
*/
function unwindStrategy(
string calldata name,
uint256 amount,
uint8 index
) external;
/**
* @notice Return liquidity to a pool
* @notice Typically used to refill a liquidity pool's reserve
* @dev This should only be callable by the `MetaPoolToken`
* @param pool The `IReservePool` to transfer to
* @param amount The amount of the pool's underlyer token to transer
*/
function transferToPool(address pool, uint256 amount) external;
/**
* @notice Swap tokens with a registered `ISwap`
* @notice Used to compound reward tokens
* @notice Used to rebalance underlyer tokens
* @param name The name of the `IZap`
* @param amount The amount of tokens to swap
* @param minAmount The minimum amount of tokens to receive from the swap
*/
function swap(
string calldata name,
uint256 amount,
uint256 minAmount
) external;
/**
* @notice Claim reward tokens with a registered `IZap`
* @param name The name of the `IZap`
*/
function claim(string calldata name) external;
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IZap} from "./IZap.sol";
/**
* @notice For managing a collection of `IZap` contracts
*/
interface IZapRegistry {
/** @notice Log when a new `IZap` is registered */
event ZapRegistered(IZap zap);
/** @notice Log when an `IZap` is removed */
event ZapRemoved(string name);
/**
* @notice Add a new `IZap` to the registry
* @dev Should not allow duplicate swaps
* @param zap The new `IZap`
*/
function registerZap(IZap zap) external;
/**
* @notice Remove an `IZap` from the registry
* @param name The name of the `IZap` (see `INameIdentifier`)
*/
function removeZap(string calldata name) external;
/**
* @notice Get the names of all registered `IZap`
* @return An array of `IZap` names
*/
function zapNames() external view returns (string[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {ISwap} from "./ISwap.sol";
/**
* @notice For managing a collection of `ISwap` contracts
*/
interface ISwapRegistry {
/** @notice Log when a new `ISwap` is registered */
event SwapRegistered(ISwap swap);
/** @notice Log when an `ISwap` is removed */
event SwapRemoved(string name);
/**
* @notice Add a new `ISwap` to the registry
* @dev Should not allow duplicate swaps
* @param swap The new `ISwap`
*/
function registerSwap(ISwap swap) external;
/**
* @notice Remove an `ISwap` from the registry
* @param name The name of the `ISwap` (see `INameIdentifier`)
*/
function removeSwap(string calldata name) external;
/**
* @notice Get the names of all registered `ISwap`
* @return An array of `ISwap` names
*/
function swapNames() external view returns (string[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice the stablecoin pool contract
*/
interface IStableSwap3Pool {
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy // solhint-disable-line func-param-name-mixedcase
) external;
function coins(uint256 coin) external view returns (address);
// solhint-disable-next-line func-name-mixedcase
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {CurveAllocationBase, CurveAllocationBase3} from "./CurveAllocationBase.sol";
import {CurveAllocationBase2} from "./CurveAllocationBase2.sol";
import {CurveAllocationBase4} from "./CurveAllocationBase4.sol";
import {CurveGaugeZapBase} from "./CurveGaugeZapBase.sol";
import {CurveZapBase} from "./CurveZapBase.sol";
import {OldCurveAllocationBase2} from "./OldCurveAllocationBase2.sol";
import {OldCurveAllocationBase3} from "./OldCurveAllocationBase3.sol";
import {OldCurveAllocationBase4} from "./OldCurveAllocationBase4.sol";
import {TestCurveZap} from "./TestCurveZap.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20, IDetailedERC20} from "contracts/common/Imports.sol";
/**
* @notice An asset allocation for tokens not stored in a protocol
* @dev `IZap`s and `ISwap`s register these separate from other allocations
* @dev Unlike other asset allocations, new tokens can be added or removed
* @dev Registration can override `symbol` and `decimals` manually because
* they are optional in the ERC20 standard.
*/
interface IErc20Allocation {
/** @notice Log when an ERC20 allocation is registered */
event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals);
/** @notice Log when an ERC20 allocation is removed */
event Erc20TokenRemoved(IERC20 token);
/**
* @notice Add a new ERC20 token to the asset allocation
* @dev Should not allow duplicate tokens
* @param token The new token
*/
function registerErc20Token(IDetailedERC20 token) external;
/**
* @notice Add a new ERC20 token to the asset allocation
* @dev Should not allow duplicate tokens
* @param token The new token
* @param symbol Override the token symbol
*/
function registerErc20Token(IDetailedERC20 token, string calldata symbol)
external;
/**
* @notice Add a new ERC20 token to the asset allocation
* @dev Should not allow duplicate tokens
* @param token The new token
* @param symbol Override the token symbol
* @param decimals Override the token decimals
*/
function registerErc20Token(
IERC20 token,
string calldata symbol,
uint8 decimals
) external;
/**
* @notice Remove an ERC20 token from the asset allocation
* @param token The token to remove
*/
function removeErc20Token(IERC20 token) external;
/**
* @notice Check if an ERC20 token is registered
* @param token The token to check
* @return `true` if the token is registered, `false` otherwise
*/
function isErc20TokenRegistered(IERC20 token) external view returns (bool);
/**
* @notice Check if multiple ERC20 tokens are ALL registered
* @param tokens An array of tokens to check
* @return `true` if every token is registered, `false` otherwise
*/
function isErc20TokenRegistered(IERC20[] calldata tokens)
external
view
returns (bool);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Interface used by Chainlink to aggregate allocations and compute TVL
*/
interface IChainlinkRegistry {
/**
* @notice Get all IDs from registered asset allocations
* @notice Each ID is a unique asset allocation and token index pair
* @dev Should contain no duplicate IDs
* @return list of all IDs
*/
function getAssetAllocationIds() external view returns (bytes32[] memory);
/**
* @notice Get the LP Account's balance for an asset allocation ID
* @param allocationId The ID to fetch the balance for
* @return The balance for the LP Account
*/
function balanceOf(bytes32 allocationId) external view returns (uint256);
/**
* @notice Get the symbol for an allocation ID's underlying token
* @param allocationId The ID to fetch the symbol for
* @return The underlying token symbol
*/
function symbolOf(bytes32 allocationId)
external
view
returns (string memory);
/**
* @notice Get the decimals for an allocation ID's underlying token
* @param allocationId The ID to fetch the decimals for
* @return The underlying token decimals
*/
function decimalsOf(bytes32 allocationId) external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IAssetAllocation} from "contracts/common/Imports.sol";
/**
* @notice For managing a collection of `IAssetAllocation` contracts
*/
interface IAssetAllocationRegistry {
/** @notice Log when an asset allocation is registered */
event AssetAllocationRegistered(IAssetAllocation assetAllocation);
/** @notice Log when an asset allocation is removed */
event AssetAllocationRemoved(string name);
/**
* @notice Add a new asset allocation to the registry
* @dev Should not allow duplicate asset allocations
* @param assetAllocation The new asset allocation
*/
function registerAssetAllocation(IAssetAllocation assetAllocation) external;
/**
* @notice Remove an asset allocation from the registry
* @param name The name of the asset allocation (see `INameIdentifier`)
*/
function removeAssetAllocation(string memory name) external;
/**
* @notice Check if multiple asset allocations are ALL registered
* @param allocationNames An array of asset allocation names
* @return `true` if every allocation is registered, otherwise `false`
*/
function isAssetAllocationRegistered(string[] calldata allocationNames)
external
view
returns (bool);
/**
* @notice Get the registered asset allocation with a given name
* @param name The asset allocation name
* @return The asset allocation
*/
function getAssetAllocation(string calldata name)
external
view
returns (IAssetAllocation);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IAssetAllocation} from "contracts/common/Imports.sol";
abstract contract AssetAllocationBase is IAssetAllocation {
function numberOfTokens() external view override returns (uint256) {
return tokens().length;
}
function symbolOf(uint8 tokenIndex)
public
view
override
returns (string memory)
{
return tokens()[tokenIndex].symbol;
}
function decimalsOf(uint8 tokenIndex) public view override returns (uint8) {
return tokens()[tokenIndex].decimals;
}
function addressOf(uint8 tokenIndex) public view returns (address) {
return tokens()[tokenIndex].token;
}
function tokens() public view virtual override returns (TokenData[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {Address} from "contracts/libraries/Imports.sol";
import {AssetAllocationBase} from "./AssetAllocationBase.sol";
/**
* @notice Asset allocation with underlying tokens that cannot be added/removed
*/
abstract contract ImmutableAssetAllocation is AssetAllocationBase {
using Address for address;
constructor() public {
_validateTokens(_getTokenData());
}
function tokens() public view override returns (TokenData[] memory) {
TokenData[] memory tokens_ = _getTokenData();
return tokens_;
}
/**
* @notice Verifies that a `TokenData` array works with the `TvlManager`
* @dev Reverts when there is invalid `TokenData`
* @param tokens_ The array of `TokenData`
*/
function _validateTokens(TokenData[] memory tokens_) internal view virtual {
// length restriction due to encoding logic for allocation IDs
require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS");
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i].token;
_validateTokenAddress(token);
string memory symbol = tokens_[i].symbol;
require(bytes(symbol).length != 0, "INVALID_SYMBOL");
}
// TODO: check for duplicate tokens
}
/**
* @notice Verify that a token is a contract
* @param token The token to verify
*/
function _validateTokenAddress(address token) internal view virtual {
require(token.isContract(), "INVALID_ADDRESS");
}
/**
* @notice Get the immutable array of underlying `TokenData`
* @dev Should be implemented in child contracts with a hardcoded array
* @return The array of `TokenData`
*/
function _getTokenData() internal pure virtual returns (TokenData[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
IERC20,
IDetailedERC20,
AccessControl,
INameIdentifier,
ReentrancyGuard
} from "contracts/common/Imports.sol";
import {Address, EnumerableSet} from "contracts/libraries/Imports.sol";
import {IAddressRegistryV2} from "contracts/registry/Imports.sol";
import {ILockingOracle} from "contracts/oracle/Imports.sol";
import {IErc20Allocation} from "./IErc20Allocation.sol";
import {AssetAllocationBase} from "./AssetAllocationBase.sol";
abstract contract Erc20AllocationConstants is INameIdentifier {
string public constant override NAME = "erc20Allocation";
}
contract Erc20Allocation is
IErc20Allocation,
AssetAllocationBase,
Erc20AllocationConstants,
AccessControl,
ReentrancyGuard
{
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
IAddressRegistryV2 public addressRegistry;
EnumerableSet.AddressSet private _tokenAddresses;
mapping(address => TokenData) private _tokenToData;
/** @notice Log when the address registry is changed */
event AddressRegistryChanged(address);
constructor(address addressRegistry_) public {
_setAddressRegistry(addressRegistry_);
_setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress());
_setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress());
_setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress());
_setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress());
}
/**
* @notice Set the new address registry
* @param addressRegistry_ The new address registry
*/
function emergencySetAddressRegistry(address addressRegistry_)
external
nonReentrant
onlyEmergencyRole
{
_setAddressRegistry(addressRegistry_);
}
function registerErc20Token(IDetailedERC20 token)
external
override
nonReentrant
onlyAdminOrContractRole
{
string memory symbol = token.symbol();
uint8 decimals = token.decimals();
_registerErc20Token(token, symbol, decimals);
}
function registerErc20Token(IDetailedERC20 token, string calldata symbol)
external
override
nonReentrant
onlyAdminRole
{
uint8 decimals = token.decimals();
_registerErc20Token(token, symbol, decimals);
}
function registerErc20Token(
IERC20 token,
string calldata symbol,
uint8 decimals
) external override nonReentrant onlyAdminRole {
_registerErc20Token(token, symbol, decimals);
}
function removeErc20Token(IERC20 token)
external
override
nonReentrant
onlyAdminRole
{
_tokenAddresses.remove(address(token));
delete _tokenToData[address(token)];
_lockOracleAdapter();
emit Erc20TokenRemoved(token);
}
function isErc20TokenRegistered(IERC20 token)
external
view
override
returns (bool)
{
return _tokenAddresses.contains(address(token));
}
function isErc20TokenRegistered(IERC20[] calldata tokens)
external
view
override
returns (bool)
{
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
if (!_tokenAddresses.contains(address(tokens[i]))) {
return false;
}
}
return true;
}
function balanceOf(address account, uint8 tokenIndex)
external
view
override
returns (uint256)
{
address token = addressOf(tokenIndex);
return IERC20(token).balanceOf(account);
}
function tokens() public view override returns (TokenData[] memory) {
TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length());
for (uint256 i = 0; i < _tokens.length; i++) {
address tokenAddress = _tokenAddresses.at(i);
_tokens[i] = _tokenToData[tokenAddress];
}
return _tokens;
}
function _setAddressRegistry(address addressRegistry_) internal {
require(addressRegistry_.isContract(), "INVALID_ADDRESS");
addressRegistry = IAddressRegistryV2(addressRegistry_);
emit AddressRegistryChanged(addressRegistry_);
}
function _registerErc20Token(
IERC20 token,
string memory symbol,
uint8 decimals
) internal {
require(address(token).isContract(), "INVALID_ADDRESS");
require(bytes(symbol).length != 0, "INVALID_SYMBOL");
_tokenAddresses.add(address(token));
_tokenToData[address(token)] = TokenData(
address(token),
symbol,
decimals
);
_lockOracleAdapter();
emit Erc20TokenRegistered(token, symbol, decimals);
}
/**
* @notice Lock the `OracleAdapter` for the default period of time
* @dev Locking protects against front-running while Chainlink updates
*/
function _lockOracleAdapter() internal {
ILockingOracle oracleAdapter =
ILockingOracle(addressRegistry.oracleAdapterAddress());
oracleAdapter.lock();
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IAddressRegistryV2} from "./IAddressRegistryV2.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol";
import {IOracleAdapter} from "./IOracleAdapter.sol";
import {IOverrideOracle} from "./IOverrideOracle.sol";
import {ILockingOracle} from "./ILockingOracle.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice The address registry has two important purposes, one which
* is fairly concrete and another abstract.
*
* 1. The registry enables components of the APY.Finance system
* and external systems to retrieve core addresses reliably
* even when the functionality may move to a different
* address.
*
* 2. The registry also makes explicit which contracts serve
* as primary entrypoints for interacting with different
* components. Not every contract is registered here, only
* the ones properly deserving of an identifier. This helps
* define explicit boundaries between groups of contracts,
* each of which is logically cohesive.
*/
interface IAddressRegistryV2 {
/**
* @notice Log when a new address is registered
* @param id The ID of the new address
* @param _address The new address
*/
event AddressRegistered(bytes32 id, address _address);
/**
* @notice Log when an address is removed from the registry
* @param id The ID of the address
* @param _address The address
*/
event AddressDeleted(bytes32 id, address _address);
/**
* @notice Register address with identifier
* @dev Using an existing ID will replace the old address with new
* @dev Currently there is no way to remove an ID, as attempting to
* register the zero address will revert.
*/
function registerAddress(bytes32 id, address address_) external;
/**
* @notice Registers multiple address at once
* @dev Convenient method to register multiple addresses at once.
* @param ids Ids to register addresses under
* @param addresses Addresses to register
*/
function registerMultipleAddresses(
bytes32[] calldata ids,
address[] calldata addresses
) external;
/**
* @notice Removes a registered id and it's associated address
* @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`.
* @param id ID to remove along with it's associated address
*/
function deleteAddress(bytes32 id) external;
/**
* @notice Returns the list of all registered identifiers.
* @return List of identifiers
*/
function getIds() external view returns (bytes32[] memory);
/**
* @notice Returns the list of all registered identifiers
* @param id Component identifier
* @return The current address represented by an identifier
*/
function getAddress(bytes32 id) external view returns (address);
/**
* @notice Returns the TVL Manager Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return TVL Manager Address
*/
function tvlManagerAddress() external view returns (address);
/**
* @notice Returns the Chainlink Registry Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Chainlink Registry Address
*/
function chainlinkRegistryAddress() external view returns (address);
/**
* @notice Returns the DAI Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return DAI Pool Address
*/
function daiPoolAddress() external view returns (address);
/**
* @notice Returns the USDC Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return USDC Pool Address
*/
function usdcPoolAddress() external view returns (address);
/**
* @notice Returns the USDT Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return USDT Pool Address
*/
function usdtPoolAddress() external view returns (address);
/**
* @notice Returns the MAPT Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return MAPT Pool Address
*/
function mAptAddress() external view returns (address);
/**
* @notice Returns the LP Account Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return LP Account Address
*/
function lpAccountAddress() external view returns (address);
/**
* @notice Returns the LP Safe Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return LP Safe Address
*/
function lpSafeAddress() external view returns (address);
/**
* @notice Returns the Admin Safe Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Admin Safe Address
*/
function adminSafeAddress() external view returns (address);
/**
* @notice Returns the Emergency Safe Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Emergency Safe Address
*/
function emergencySafeAddress() external view returns (address);
/**
* @notice Returns the Oracle Adapter Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Oracle Adapter Address
*/
function oracleAdapterAddress() external view returns (address);
/**
* @notice Returns the ERC20 Allocation Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return ERC20 Allocation Address
*/
function erc20AllocationAddress() external view returns (address);
}
/**
SPDX-License-Identifier: UNLICENSED
----------------------------------
---- APY.Finance comments --------
----------------------------------
Due to pragma being fixed at 0.6.6, we had to copy over this contract
and fix the imports.
original path: @chainlink/contracts/src/v0.6/FluxAggregator.sol
npm package version: 0.0.9
*/
pragma solidity 0.6.11;
import "@chainlink/contracts/src/v0.6/Median.sol";
import "@chainlink/contracts/src/v0.6/Owned.sol";
import "@chainlink/contracts/src/v0.6/SafeMath128.sol";
import "@chainlink/contracts/src/v0.6/SafeMath32.sol";
import "@chainlink/contracts/src/v0.6/SafeMath64.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol";
import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol";
/* solhint-disable */
/**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/
contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 public immutable minSubmissionValue;
int256 public immutable maxSubmissionValue;
uint256 public constant override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 private constant RESERVE_ROUNDS = 2;
uint256 private constant MAX_ORACLE_COUNT = 77;
uint32 private constant ROUND_MAX = 2**32 - 1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string private constant V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(uint256 indexed amount);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(address indexed oracle, address indexed newAdmin);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(address indexed previous, address indexed current);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission) external {
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(
_submission >= minSubmissionValue,
"value below minSubmissionValue"
);
require(
_submission <= maxSubmissionValue,
"value above maxSubmissionValue"
);
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
) external onlyOwner() {
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(
_added.length == _addedAdmins.length,
"need same oracle and admin count"
);
require(
uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT,
"max oracles allowed"
);
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
timeout
);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
) public onlyOwner() {
uint32 oracleNum = oracleCount(); // Save on storage reads
require(
_maxSubmissions >= _minSubmissions,
"max must equal/exceed min"
);
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(
oracleNum == 0 || oracleNum > _restartDelay,
"delay cannot exceed total"
);
require(
recordedFunds.available >= requiredReserve(_paymentAmount),
"insufficient funds for payment"
);
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds() external view returns (uint128) {
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds() external view returns (uint128) {
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds() public {
Funds memory funds = recordedFunds;
uint256 nowAvailable =
linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer() public view virtual override returns (int256) {
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp() public view virtual override returns (uint256) {
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound() public view virtual override returns (uint256) {
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(
r.answeredInRound > 0 && validRoundId(_roundId),
V3_NO_DATA_ERROR
);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(
address _oracle,
address _recipient,
uint256 _amount
) external {
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(
available.sub(requiredReserve(paymentAmount)) >= _amount,
"insufficient reserve funds"
);
require(
linkToken.transfer(_recipient, _amount),
"token transfer failed"
);
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle) external view returns (address) {
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin) external {
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle) external {
require(
oracles[_oracle].pendingAdmin == msg.sender,
"only callable by pending admin"
);
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound() external returns (uint80) {
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(
rounds[current].updatedAt > 0 || timedOut(current),
"prev round must be supersedable"
);
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(
address _requester,
bool _authorized,
uint32 _delay
) external onlyOwner() {
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(
address,
uint256,
bytes calldata _data
) external {
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator) public onlyOwner() {
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId) private {
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails =
RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId) private {
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId) private {
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(
_roundId > lastStarted + requesters[msg.sender].delay ||
lastStarted == 0,
"must delay requests"
);
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId) private {
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return
acceptingSubmissions(_queriedRoundId) &&
validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return
delayed(_oracle, _queriedRoundId) &&
validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede =
oracle.lastReportedRound == reportingRoundId ||
!acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (
details[_roundId].submissions.length <
details[_roundId].minSubmissions
) {
return (false, 0);
}
int256 newAnswer =
Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(uint32 _roundId, int256 _newAnswer) private {
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try
av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
)
{} catch {}
}
function payOracle(uint32 _roundId) private {
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(
payment
);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId) private {
require(
acceptingSubmissions(_roundId),
"round not accepting submissions"
);
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId) private {
if (
details[_roundId].submissions.length <
details[_roundId].maxSubmissions
) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId) private view returns (bool) {
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return
startedAt > 0 &&
roundTimeout > 0 &&
startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle) private view returns (uint32) {
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment) private view returns (uint256) {
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(address _oracle, address _admin) private {
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(
oracles[_oracle].admin == address(0) ||
oracles[_oracle].admin == _admin,
"owner cannot overwrite admin"
);
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(address _oracle) private {
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId)
return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId)
return "cannot report on previous rounds";
if (
_roundId != rrId &&
_roundId != rrId.add(1) &&
!previousAndCurrentUnanswered(_roundId, rrId)
) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1)))
return "previous round not supersedable";
}
function supersedable(uint32 _roundId) private view returns (bool) {
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle) private view returns (bool) {
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId) private view returns (bool) {
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId) private view returns (bool) {
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId) private view returns (bool) {
return _roundId <= ROUND_MAX;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Interface for securely interacting with Chainlink aggregators
*/
interface IOracleAdapter {
struct Value {
uint256 value;
uint256 periodEnd;
}
/// @notice Event fired when asset's pricing source (aggregator) is updated
event AssetSourceUpdated(address indexed asset, address indexed source);
/// @notice Event fired when the TVL aggregator address is updated
event TvlSourceUpdated(address indexed source);
/**
* @notice Set the TVL source (aggregator)
* @param source The new TVL source (aggregator)
*/
function emergencySetTvlSource(address source) external;
/**
* @notice Set an asset's price source (aggregator)
* @param asset The asset to change the source of
* @param source The new source (aggregator)
*/
function emergencySetAssetSource(address asset, address source) external;
/**
* @notice Set multiple assets' pricing sources
* @param assets An array of assets (tokens)
* @param sources An array of price sources (aggregators)
*/
function emergencySetAssetSources(
address[] memory assets,
address[] memory sources
) external;
/**
* @notice Retrieve the asset's price from its pricing source
* @param asset The asset address
* @return The price of the asset
*/
function getAssetPrice(address asset) external view returns (uint256);
/**
* @notice Retrieve the deployed TVL from the TVL aggregator
* @return The TVL
*/
function getTvl() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IOracleAdapter} from "./IOracleAdapter.sol";
interface IOverrideOracle is IOracleAdapter {
/**
* @notice Event fired when asset value is set manually
* @param asset The asset that is being overridden
* @param value The new value used for the override
* @param period The number of blocks the override will be active for
* @param periodEnd The block on which the override ends
*/
event AssetValueSet(
address asset,
uint256 value,
uint256 period,
uint256 periodEnd
);
/**
* @notice Event fired when manually submitted asset value is
* invalidated, allowing usual Chainlink pricing.
*/
event AssetValueUnset(address asset);
/**
* @notice Event fired when deployed TVL is set manually
* @param value The new value used for the override
* @param period The number of blocks the override will be active for
* @param periodEnd The block on which the override ends
*/
event TvlSet(uint256 value, uint256 period, uint256 periodEnd);
/**
* @notice Event fired when manually submitted TVL is
* invalidated, allowing usual Chainlink pricing.
*/
event TvlUnset();
/**
* @notice Manually override the asset pricing source with a value
* @param asset The asset that is being overriden
* @param value asset value to return instead of from Chainlink
* @param period length of time, in number of blocks, to use manual override
*/
function emergencySetAssetValue(
address asset,
uint256 value,
uint256 period
) external;
/**
* @notice Revoke manually set value, allowing usual Chainlink pricing
* @param asset address of asset to price
*/
function emergencyUnsetAssetValue(address asset) external;
/**
* @notice Manually override the TVL source with a value
* @param value TVL to return instead of from Chainlink
* @param period length of time, in number of blocks, to use manual override
*/
function emergencySetTvl(uint256 value, uint256 period) external;
/// @notice Revoke manually set value, allowing usual Chainlink pricing
function emergencyUnsetTvl() external;
/// @notice Check if TVL has active manual override
function hasTvlOverride() external view returns (bool);
/**
* @notice Check if asset has active manual override
* @param asset address of the asset
* @return `true` if manual override is active
*/
function hasAssetOverride(address asset) external view returns (bool);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IOracleAdapter} from "./IOracleAdapter.sol";
/**
* @notice For an `IOracleAdapter` that can be locked and unlocked
*/
interface ILockingOracle is IOracleAdapter {
/// @notice Event fired when using the default lock
event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd);
/// @notice Event fired when using a specified lock period
event Locked(address locker, uint256 activePeriod, uint256 lockEnd);
/// @notice Event fired when changing the default locking period
event DefaultLockPeriodChanged(uint256 newPeriod);
/// @notice Event fired when unlocking the adapter
event Unlocked();
/// @notice Event fired when updating the threshold for stale data
event ChainlinkStalePeriodUpdated(uint256 period);
/// @notice Block price/value retrieval for the default locking duration
function lock() external;
/**
* @notice Block price/value retrieval for the specified duration.
* @param period number of blocks to block retrieving values
*/
function lockFor(uint256 period) external;
/**
* @notice Unblock price/value retrieval. Should only be callable
* by the Emergency Safe.
*/
function emergencyUnlock() external;
/**
* @notice Set the length of time before values can be retrieved.
* @param newPeriod number of blocks before values can be retrieved
*/
function setDefaultLockPeriod(uint256 newPeriod) external;
/**
* @notice Set the length of time before an agg value is considered stale.
* @param chainlinkStalePeriod_ the length of time in seconds
*/
function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external;
/**
* @notice Get the length of time, in number of blocks, before values
* can be retrieved.
*/
function defaultLockPeriod() external returns (uint256 period);
/// @notice Check if the adapter is blocked from retrieving values.
function isLocked() external view returns (bool);
}
pragma solidity ^0.6.0;
import "./vendor/SafeMath.sol";
import "./SignedSafeMath.sol";
library Median {
using SignedSafeMath for int256;
int256 constant INT_MAX = 2**255-1;
/**
* @notice Returns the sorted middle, or the average of the two middle indexed items if the
* array has an even number of elements.
* @dev The list passed as an argument isn't modified.
* @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs
* the runtime is O(n^2).
* @param list The list of elements to compare
*/
function calculate(int256[] memory list)
internal
pure
returns (int256)
{
return calculateInplace(copy(list));
}
/**
* @notice See documentation for function calculate.
* @dev The list passed as an argument may be permuted.
*/
function calculateInplace(int256[] memory list)
internal
pure
returns (int256)
{
require(0 < list.length, "list must not be empty");
uint256 len = list.length;
uint256 middleIndex = len / 2;
if (len % 2 == 0) {
int256 median1;
int256 median2;
(median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex);
return SignedSafeMath.avg(median1, median2);
} else {
return quickselect(list, 0, len - 1, middleIndex);
}
}
/**
* @notice Maximum length of list that shortSelectTwo can handle
*/
uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7;
/**
* @notice Select the k1-th and k2-th element from list of length at most 7
* @dev Uses an optimal sorting network
*/
function shortSelectTwo(
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
private
pure
returns (int256 k1th, int256 k2th)
{
// Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network)
// for lists of length 7. Network layout is taken from
// http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg
uint256 len = hi + 1 - lo;
int256 x0 = list[lo + 0];
int256 x1 = 1 < len ? list[lo + 1] : INT_MAX;
int256 x2 = 2 < len ? list[lo + 2] : INT_MAX;
int256 x3 = 3 < len ? list[lo + 3] : INT_MAX;
int256 x4 = 4 < len ? list[lo + 4] : INT_MAX;
int256 x5 = 5 < len ? list[lo + 5] : INT_MAX;
int256 x6 = 6 < len ? list[lo + 6] : INT_MAX;
if (x0 > x1) {(x0, x1) = (x1, x0);}
if (x2 > x3) {(x2, x3) = (x3, x2);}
if (x4 > x5) {(x4, x5) = (x5, x4);}
if (x0 > x2) {(x0, x2) = (x2, x0);}
if (x1 > x3) {(x1, x3) = (x3, x1);}
if (x4 > x6) {(x4, x6) = (x6, x4);}
if (x1 > x2) {(x1, x2) = (x2, x1);}
if (x5 > x6) {(x5, x6) = (x6, x5);}
if (x0 > x4) {(x0, x4) = (x4, x0);}
if (x1 > x5) {(x1, x5) = (x5, x1);}
if (x2 > x6) {(x2, x6) = (x6, x2);}
if (x1 > x4) {(x1, x4) = (x4, x1);}
if (x3 > x6) {(x3, x6) = (x6, x3);}
if (x2 > x4) {(x2, x4) = (x4, x2);}
if (x3 > x5) {(x3, x5) = (x5, x3);}
if (x3 > x4) {(x3, x4) = (x4, x3);}
uint256 index1 = k1 - lo;
if (index1 == 0) {k1th = x0;}
else if (index1 == 1) {k1th = x1;}
else if (index1 == 2) {k1th = x2;}
else if (index1 == 3) {k1th = x3;}
else if (index1 == 4) {k1th = x4;}
else if (index1 == 5) {k1th = x5;}
else if (index1 == 6) {k1th = x6;}
else {revert("k1 out of bounds");}
uint256 index2 = k2 - lo;
if (k1 == k2) {return (k1th, k1th);}
else if (index2 == 0) {return (k1th, x0);}
else if (index2 == 1) {return (k1th, x1);}
else if (index2 == 2) {return (k1th, x2);}
else if (index2 == 3) {return (k1th, x3);}
else if (index2 == 4) {return (k1th, x4);}
else if (index2 == 5) {return (k1th, x5);}
else if (index2 == 6) {return (k1th, x6);}
else {revert("k2 out of bounds");}
}
/**
* @notice Selects the k-th ranked element from list, looking only at indices between lo and hi
* (inclusive). Modifies list in-place.
*/
function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k)
private
pure
returns (int256 kth)
{
require(lo <= k);
require(k <= hi);
while (lo < hi) {
if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {
int256 ignore;
(kth, ignore) = shortSelectTwo(list, lo, hi, k, k);
return kth;
}
uint256 pivotIndex = partition(list, lo, hi);
if (k <= pivotIndex) {
// since pivotIndex < (original hi passed to partition),
// termination is guaranteed in this case
hi = pivotIndex;
} else {
// since (original lo passed to partition) <= pivotIndex,
// termination is guaranteed in this case
lo = pivotIndex + 1;
}
}
return list[lo];
}
/**
* @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between
* lo and hi (inclusive). Modifies list in-place.
*/
function quickselectTwo(
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
internal // for testing
pure
returns (int256 k1th, int256 k2th)
{
require(k1 < k2);
require(lo <= k1 && k1 <= hi);
require(lo <= k2 && k2 <= hi);
while (true) {
if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {
return shortSelectTwo(list, lo, hi, k1, k2);
}
uint256 pivotIdx = partition(list, lo, hi);
if (k2 <= pivotIdx) {
hi = pivotIdx;
} else if (pivotIdx < k1) {
lo = pivotIdx + 1;
} else {
assert(k1 <= pivotIdx && pivotIdx < k2);
k1th = quickselect(list, lo, pivotIdx, k1);
k2th = quickselect(list, pivotIdx + 1, hi, k2);
return (k1th, k2th);
}
}
}
/**
* @notice Partitions list in-place using Hoare's partitioning scheme.
* Only elements of list between indices lo and hi (inclusive) will be modified.
* Returns an index i, such that:
* - lo <= i < hi
* - forall j in [lo, i]. list[j] <= list[i]
* - forall j in [i, hi]. list[i] <= list[j]
*/
function partition(int256[] memory list, uint256 lo, uint256 hi)
private
pure
returns (uint256)
{
// We don't care about overflow of the addition, because it would require a list
// larger than any feasible computer's memory.
int256 pivot = list[(lo + hi) / 2];
lo -= 1; // this can underflow. that's intentional.
hi += 1;
while (true) {
do {
lo += 1;
} while (list[lo] < pivot);
do {
hi -= 1;
} while (list[hi] > pivot);
if (lo < hi) {
(list[lo], list[hi]) = (list[hi], list[lo]);
} else {
// Let orig_lo and orig_hi be the original values of lo and hi passed to partition.
// Then, hi < orig_hi, because hi decreases *strictly* monotonically
// in each loop iteration and
// - either list[orig_hi] > pivot, in which case the first loop iteration
// will achieve hi < orig_hi;
// - or list[orig_hi] <= pivot, in which case at least two loop iterations are
// needed:
// - lo will have to stop at least once in the interval
// [orig_lo, (orig_lo + orig_hi)/2]
// - (orig_lo + orig_hi)/2 < orig_hi
return hi;
}
}
}
/**
* @notice Makes an in-memory copy of the array passed in
* @param list Reference to the array to be copied
*/
function copy(int256[] memory list)
private
pure
returns(int256[] memory)
{
int256[] memory list2 = new int256[](list.length);
for (uint256 i = 0; i < list.length; i++) {
list2[i] = list[i];
}
return list2;
}
}
pragma solidity ^0.6.0;
/**
* @title The Owned contract
* @notice A contract with helpers for basic contract ownership.
*/
contract Owned {
address payable public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 128 bit integers.
*/
library SafeMath128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "SafeMath: subtraction overflow");
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 32 bit integers.
*/
library SafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
require(b <= a, "SafeMath: subtraction overflow");
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// 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;
}
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 64 bit integers.
*/
library SafeMath64 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
require(b <= a, "SafeMath: subtraction overflow");
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
// 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;
}
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
pragma solidity ^0.6.0;
interface AggregatorValidatorInterface {
function validate(
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external returns (bool);
}
pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
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) {
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;
}
}
pragma solidity ^0.6.0;
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts on 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 Adds two signed integers, reverts on 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;
}
/**
* @notice Computes average of two signed integers, ensuring that the computation
* doesn't overflow.
* @dev If the result is not an integer, it is rounded towards zero. For example,
* avg(-3, -4) = -3
*/
function avg(int256 _a, int256 _b)
internal
pure
returns (int256)
{
if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) {
return add(_a, _b) / 2;
}
int256 remainder = (_a % 2 + _b % 2) / 2;
return add(add(_a / 2, _b / 2), remainder);
}
}
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
IStableSwap,
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
/**
* @title Periphery Contract for the Curve 3pool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
contract CurveAllocationBase {
using SafeMath for uint256;
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param stableSwap the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param lpToken the LP token representing the share of the pool
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IStableSwap stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken,
uint256 coin
) public view returns (uint256 balance) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(stableSwap, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) =
getLpTokenShare(account, stableSwap, gauge, lpToken);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IStableSwap stableSwap, uint256 coin)
public
view
returns (uint256)
{
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
return stableSwap.balances(coin);
}
function getLpTokenShare(
address account,
IStableSwap stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
}
// solhint-disable-next-line no-empty-blocks
contract CurveAllocationBase3 is CurveAllocationBase {
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
IStableSwap2,
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
/**
* @title Periphery Contract for the Curve 3pool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
contract CurveAllocationBase2 {
using SafeMath for uint256;
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param stableSwap the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param lpToken the LP token representing the share of the pool
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IStableSwap2 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken,
uint256 coin
) public view returns (uint256 balance) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(stableSwap, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) =
getLpTokenShare(account, stableSwap, gauge, lpToken);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IStableSwap2 stableSwap, uint256 coin)
public
view
returns (uint256)
{
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
return stableSwap.balances(coin);
}
function getLpTokenShare(
address account,
IStableSwap2 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
IStableSwap4,
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
/**
* @title Periphery Contract for the Curve 3pool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
contract CurveAllocationBase4 {
using SafeMath for uint256;
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param stableSwap the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param lpToken the LP token representing the share of the pool
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IStableSwap4 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken,
uint256 coin
) public view returns (uint256 balance) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(stableSwap, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) =
getLpTokenShare(account, stableSwap, gauge, lpToken);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IStableSwap4 stableSwap, uint256 coin)
public
view
returns (uint256)
{
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
return stableSwap.balances(coin);
}
function getLpTokenShare(
address account,
IStableSwap4 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IZap} from "contracts/lpaccount/Imports.sol";
import {
IAssetAllocation,
IERC20,
IDetailedERC20
} from "contracts/common/Imports.sol";
import {SafeERC20} from "contracts/libraries/Imports.sol";
import {
ILiquidityGauge,
ITokenMinter
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
import {CurveZapBase} from "contracts/protocols/curve/common/CurveZapBase.sol";
abstract contract CurveGaugeZapBase is IZap, CurveZapBase {
using SafeERC20 for IERC20;
address internal constant MINTER_ADDRESS =
0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
address internal immutable LP_ADDRESS;
address internal immutable GAUGE_ADDRESS;
constructor(
address swapAddress,
address lpAddress,
address gaugeAddress,
uint256 denominator,
uint256 slippage,
uint256 nCoins
)
public
CurveZapBase(swapAddress, denominator, slippage, nCoins)
// solhint-disable-next-line no-empty-blocks
{
LP_ADDRESS = lpAddress;
GAUGE_ADDRESS = gaugeAddress;
}
function getLpTokenBalance(address account)
external
view
override
returns (uint256)
{
return ILiquidityGauge(GAUGE_ADDRESS).balanceOf(account);
}
function _depositToGauge() internal override {
ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS);
uint256 lpBalance = IERC20(LP_ADDRESS).balanceOf(address(this));
IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, 0);
IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, lpBalance);
liquidityGauge.deposit(lpBalance);
}
function _withdrawFromGauge(uint256 amount)
internal
override
returns (uint256)
{
ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS);
liquidityGauge.withdraw(amount);
//lpBalance
return IERC20(LP_ADDRESS).balanceOf(address(this));
}
function _claim() internal override {
// claim CRV
ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS);
// claim protocol-specific rewards
_claimRewards();
}
// solhint-disable-next-line no-empty-blocks
function _claimRewards() internal virtual {}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath, SafeERC20} from "contracts/libraries/Imports.sol";
import {IZap} from "contracts/lpaccount/Imports.sol";
import {
IAssetAllocation,
IDetailedERC20,
IERC20
} from "contracts/common/Imports.sol";
import {
Curve3poolUnderlyerConstants
} from "contracts/protocols/curve/3pool/Constants.sol";
abstract contract CurveZapBase is Curve3poolUnderlyerConstants, IZap {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address internal constant CRV_ADDRESS =
0xD533a949740bb3306d119CC777fa900bA034cd52;
address internal immutable SWAP_ADDRESS;
uint256 internal immutable DENOMINATOR;
uint256 internal immutable SLIPPAGE;
uint256 internal immutable N_COINS;
constructor(
address swapAddress,
uint256 denominator,
uint256 slippage,
uint256 nCoins
) public {
SWAP_ADDRESS = swapAddress;
DENOMINATOR = denominator;
SLIPPAGE = slippage;
N_COINS = nCoins;
}
/// @param amounts array of underlyer amounts
function deployLiquidity(uint256[] calldata amounts) external override {
require(amounts.length == N_COINS, "INVALID_AMOUNTS");
uint256 totalNormalizedDeposit = 0;
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] == 0) continue;
uint256 deposit = amounts[i];
address underlyerAddress = _getCoinAtIndex(i);
uint8 decimals = IDetailedERC20(underlyerAddress).decimals();
uint256 normalizedDeposit =
deposit.mul(10**uint256(18)).div(10**uint256(decimals));
totalNormalizedDeposit = totalNormalizedDeposit.add(
normalizedDeposit
);
IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, 0);
IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, amounts[i]);
}
uint256 minAmount =
_calcMinAmount(totalNormalizedDeposit, _getVirtualPrice());
_addLiquidity(amounts, minAmount);
_depositToGauge();
}
/**
* @param amount LP token amount
* @param index underlyer index
*/
function unwindLiquidity(uint256 amount, uint8 index) external override {
require(index < N_COINS, "INVALID_INDEX");
uint256 lpBalance = _withdrawFromGauge(amount);
address underlyerAddress = _getCoinAtIndex(index);
uint8 decimals = IDetailedERC20(underlyerAddress).decimals();
uint256 minAmount =
_calcMinAmountUnderlyer(lpBalance, _getVirtualPrice(), decimals);
_removeLiquidity(lpBalance, index, minAmount);
}
function claim() external override {
_claim();
}
function sortedSymbols() public view override returns (string[] memory) {
// N_COINS is not available as a public function
// so we have to hardcode the number here
string[] memory symbols = new string[](N_COINS);
for (uint256 i = 0; i < symbols.length; i++) {
address underlyerAddress = _getCoinAtIndex(i);
symbols[i] = IDetailedERC20(underlyerAddress).symbol();
}
return symbols;
}
function _getVirtualPrice() internal view virtual returns (uint256);
function _getCoinAtIndex(uint256 i) internal view virtual returns (address);
function _addLiquidity(uint256[] calldata amounts_, uint256 minAmount)
internal
virtual;
function _removeLiquidity(
uint256 lpBalance,
uint8 index,
uint256 minAmount
) internal virtual;
function _depositToGauge() internal virtual;
function _withdrawFromGauge(uint256 amount)
internal
virtual
returns (uint256);
function _claim() internal virtual;
/**
* @dev normalizedDepositAmount the amount in same units as virtual price (18 decimals)
* @dev virtualPrice the "price", in 18 decimals, per big token unit of the LP token
* @return required minimum amount of LP token (in token wei)
*/
function _calcMinAmount(
uint256 normalizedDepositAmount,
uint256 virtualPrice
) internal view returns (uint256) {
uint256 idealLpTokenAmount =
normalizedDepositAmount.mul(1e18).div(virtualPrice);
// allow some slippage/MEV
return
idealLpTokenAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR);
}
/**
* @param lpTokenAmount the amount in the same units as Curve LP token (18 decimals)
* @param virtualPrice the "price", in 18 decimals, per big token unit of the LP token
* @param decimals the number of decimals for underlyer token
* @return required minimum amount of underlyer (in token wei)
*/
function _calcMinAmountUnderlyer(
uint256 lpTokenAmount,
uint256 virtualPrice,
uint8 decimals
) internal view returns (uint256) {
// TODO: grab LP Token decimals explicitly?
uint256 normalizedUnderlyerAmount =
lpTokenAmount.mul(virtualPrice).div(1e18);
uint256 underlyerAmount =
normalizedUnderlyerAmount.mul(10**uint256(decimals)).div(
10**uint256(18)
);
// allow some slippage/MEV
return underlyerAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR);
}
function _createErc20AllocationArray(uint256 extraAllocations)
internal
pure
returns (IERC20[] memory)
{
IERC20[] memory allocations = new IERC20[](extraAllocations.add(4));
allocations[0] = IERC20(CRV_ADDRESS);
allocations[1] = IERC20(DAI_ADDRESS);
allocations[2] = IERC20(USDC_ADDRESS);
allocations[3] = IERC20(USDT_ADDRESS);
return allocations;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
IOldStableSwap2,
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
/**
* @title Periphery Contract for the Curve 3pool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
contract OldCurveAllocationBase2 {
using SafeMath for uint256;
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param stableSwap the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param lpToken the LP token representing the share of the pool
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IOldStableSwap2 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken,
int128 coin
) public view returns (uint256 balance) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(stableSwap, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) =
getLpTokenShare(account, stableSwap, gauge, lpToken);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IOldStableSwap2 stableSwap, int128 coin)
public
view
returns (uint256)
{
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
return stableSwap.balances(coin);
}
function getLpTokenShare(
address account,
IOldStableSwap2 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {IOldStableSwap3, ILiquidityGauge} from "contracts/protocols/curve/common/interfaces/Imports.sol";
/**
* @title Periphery Contract for the Curve 3pool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
contract OldCurveAllocationBase3 {
using SafeMath for uint256;
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param stableSwap the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param lpToken the LP token representing the share of the pool
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IOldStableSwap3 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken,
int128 coin
) public view returns (uint256 balance) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(stableSwap, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(
account,
stableSwap,
gauge,
lpToken
);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IOldStableSwap3 stableSwap, int128 coin)
public
view
returns (uint256)
{
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
return stableSwap.balances(coin);
}
function getLpTokenShare(
address account,
IOldStableSwap3 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {SafeMath} from "contracts/libraries/Imports.sol";
import {IERC20} from "contracts/common/Imports.sol";
import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol";
import {
IOldStableSwap4,
ILiquidityGauge
} from "contracts/protocols/curve/common/interfaces/Imports.sol";
/**
* @title Periphery Contract for the Curve 3pool
* @author APY.Finance
* @notice This contract enables the APY.Finance system to retrieve the balance
* of an underlyer of a Curve LP token. The balance is used as part
* of the Chainlink computation of the deployed TVL. The primary
* `getUnderlyerBalance` function is invoked indirectly when a
* Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry.
*/
contract OldCurveAllocationBase4 {
using SafeMath for uint256;
/**
* @notice Returns the balance of an underlying token represented by
* an account's LP token balance.
* @param stableSwap the liquidity pool comprised of multiple underlyers
* @param gauge the staking contract for the LP tokens
* @param lpToken the LP token representing the share of the pool
* @param coin the index indicating which underlyer
* @return balance
*/
function getUnderlyerBalance(
address account,
IOldStableSwap4 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken,
int128 coin
) public view returns (uint256 balance) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
uint256 poolBalance = getPoolBalance(stableSwap, coin);
(uint256 lpTokenBalance, uint256 lpTokenSupply) =
getLpTokenShare(account, stableSwap, gauge, lpToken);
balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply);
}
function getPoolBalance(IOldStableSwap4 stableSwap, int128 coin)
public
view
returns (uint256)
{
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
return stableSwap.balances(coin);
}
function getLpTokenShare(
address account,
IOldStableSwap4 stableSwap,
ILiquidityGauge gauge,
IERC20 lpToken
) public view returns (uint256 balance, uint256 totalSupply) {
require(address(stableSwap) != address(0), "INVALID_STABLESWAP");
require(address(gauge) != address(0), "INVALID_GAUGE");
require(address(lpToken) != address(0), "INVALID_LP_TOKEN");
totalSupply = lpToken.totalSupply();
balance = lpToken.balanceOf(account);
balance = balance.add(gauge.balanceOf(account));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAssetAllocation} from "contracts/common/Imports.sol";
import {
CurveGaugeZapBase
} from "contracts/protocols/curve/common/CurveGaugeZapBase.sol";
contract TestCurveZap is CurveGaugeZapBase {
string public constant override NAME = "TestCurveZap";
address[] private _underlyers;
constructor(
address swapAddress,
address lpTokenAddress,
address liquidityGaugeAddress,
uint256 denominator,
uint256 slippage,
uint256 numOfCoins
)
public
CurveGaugeZapBase(
swapAddress,
lpTokenAddress,
liquidityGaugeAddress,
denominator,
slippage,
numOfCoins
) // solhint-disable-next-line no-empty-blocks
{}
function setUnderlyers(address[] calldata underlyers) external {
_underlyers = underlyers;
}
function getSwapAddress() external view returns (address) {
return SWAP_ADDRESS;
}
function getLpTokenAddress() external view returns (address) {
return address(LP_ADDRESS);
}
function getGaugeAddress() external view returns (address) {
return GAUGE_ADDRESS;
}
function getDenominator() external view returns (uint256) {
return DENOMINATOR;
}
function getSlippage() external view returns (uint256) {
return SLIPPAGE;
}
function getNumberOfCoins() external view returns (uint256) {
return N_COINS;
}
function calcMinAmount(uint256 totalAmount, uint256 virtualPrice)
external
view
returns (uint256)
{
return _calcMinAmount(totalAmount, virtualPrice);
}
function calcMinAmountUnderlyer(
uint256 totalAmount,
uint256 virtualPrice,
uint8 decimals
) external view returns (uint256) {
return _calcMinAmountUnderlyer(totalAmount, virtualPrice, decimals);
}
function assetAllocations() public view override returns (string[] memory) {
string[] memory allocationNames = new string[](1);
return allocationNames;
}
function erc20Allocations() public view override returns (IERC20[] memory) {
IERC20[] memory allocations = new IERC20[](0);
return allocations;
}
function _getVirtualPrice() internal view override returns (uint256) {
return 1;
}
function _getCoinAtIndex(uint256 i)
internal
view
override
returns (address)
{
return _underlyers[i];
}
function _addLiquidity(uint256[] calldata amounts, uint256 minAmount)
internal
override
// solhint-disable-next-line no-empty-blocks
{
}
function _removeLiquidity(
uint256 lpBalance,
uint8 index,
uint256 minAmount // solhint-disable-next-line no-empty-blocks
) internal override {}
} | The address registry has two important purposes, one which is fairly concrete and another abstract. 1. The registry enables components of the APY.Finance system and external systems to retrieve core addresses reliably even when the functionality may move to a different address. 2. The registry also makes explicit which contracts serve as primary entrypoints for interacting with different components. Not every contract is registered here, only the ones properly deserving of an identifier. This helps define explicit boundaries between groups of contracts, each of which is logically cohesive./ | interface IAddressRegistryV2 {
event AddressRegistered(bytes32 id, address _address);
event AddressDeleted(bytes32 id, address _address);
function registerAddress(bytes32 id, address address_) external;
function registerMultipleAddresses(
bytes32[] calldata ids,
address[] calldata addresses
) external;
function deleteAddress(bytes32 id) external;
function getIds() external view returns (bytes32[] memory);
function getAddress(bytes32 id) external view returns (address);
function tvlManagerAddress() external view returns (address);
function chainlinkRegistryAddress() external view returns (address);
function daiPoolAddress() external view returns (address);
function usdcPoolAddress() external view returns (address);
function usdtPoolAddress() external view returns (address);
function mAptAddress() external view returns (address);
function lpAccountAddress() external view returns (address);
function lpSafeAddress() external view returns (address);
function adminSafeAddress() external view returns (address);
function emergencySafeAddress() external view returns (address);
function oracleAdapterAddress() external view returns (address);
function erc20AllocationAddress() external view returns (address);
pragma solidity 0.6.11;
import {IAddressRegistryV2} from "./IAddressRegistryV2.sol";
pragma solidity 0.6.11;
import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol";
import {IOracleAdapter} from "./IOracleAdapter.sol";
import {IOverrideOracle} from "./IOverrideOracle.sol";
import {ILockingOracle} from "./ILockingOracle.sol";
pragma solidity 0.6.11;
}
| 53,156 |
./full_match/5/0x6F33c38298a1D50fdae35af410Bba2D6eF1CFead/sources/lib/revenue-distribution-token/contracts/RevenueDistributionToken.sol | As per https:eips.ethereum.org/EIPS/eip-4626security-considerations, it should round DOWN if it’s calculating the amount of assets to send to a user, given amount of shares returned. | function previewRedeem(uint256 shares_) public view virtual override returns (uint256 assets_) {
assets_ = convertToAssets(shares_);
}
| 7,053,929 |
./full_match/5/0x8D7cB3572B2719cf8e7F383D186DDf93c06b23Aa/sources/src/MembraneRegistry.sol | checks if a given id_ belongs to an instantiated membrane | function isMembrane(uint256 id_) external view returns (bool) {
return (getMembraneById[id_].tokens.length > 0);
}
| 1,933,276 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
//Truffle Imports
import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.6/vendor/Ownable.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";
import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/proxy/Initializable.sol";
import "hardhat/console.sol";
//Remix Imports
// import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
// import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/vendor/Ownable.sol";
// import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/vendor/SafeMathChainlink.sol";
// import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
// import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
// import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";
// import "./IERC20.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/Initializable.sol";
contract InfluencerAgreementFactory {
using SafeMathChainlink
for uint256;
// passed to individual agreement
struct ChainlinkVars {
bytes32 bytes32JobId;
bytes32 uintJobId;
address oracle;
LinkTokenInterface link;
uint256 oraclePayment;
}
ChainlinkVars private chainlinkVars;
InfluencerAgreement[] private influencerAgreements;
// wallet of contract creator
address payable private platformWallet;
modifier onlyOwner() {
require(platformWallet == msg.sender, 'Only Provider');
_;
}
event influencerAgreementCreated(address _newAgreement);
/**
* Network: Kovan
* Oracle: 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e
* Bytes Job ID: 50fc4215f89443d185b061e5d7af9490
* Uint Job ID: b6602d14e4734c49a5e1ce19d45a4632
* Fee: 0.1 LINK
* LINK: 0xa36085F69e2889c224210F603D836748e7dC0088
*/
constructor(address _oracle, string memory _bytesJobId, string memory _uintJobId, uint256 _fee, LinkTokenInterface _link) public {
chainlinkVars = ChainlinkVars(stringToBytes32(_bytesJobId), stringToBytes32(_uintJobId), _oracle, _link, _fee);
platformWallet = msg.sender;
}
// remix constructor
// constructor() public {
// bytes32 bytesJobId = '50fc4215f89443d185b061e5d7af9490';
// bytes32 uintJobId = 'b6602d14e4734c49a5e1ce19d45a4632';
// LinkTokenInterface LINK = LinkTokenInterface(0xa36085F69e2889c224210F603D836748e7dC0088);
// address oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
// uint linkFee = 0.1 * 10 ** 18;
// chainlinkVars = ChainlinkVars(bytesJobId, uintJobId, oracle, LINK, linkFee);
// platformWallet = msg.sender;
// }
/**
* @dev Create a new Influencer Agreement. Once it's created, all logic & flow is handled from within the InfluencerAgreement Contract
*/
// Kovan WETH
// uint128 tokenDecimals: 18
// TokenOption tokenOption: 0
// address tokenAddress: 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa // dai
// address uniswapRouter: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
// address tokenPriceFeed: 0xd04647B7CB523bb9f26730E9B6dE1174db7591Ad
// Remix [18, 0, 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0xd04647B7CB523bb9f26730E9B6dE1174db7591Ad]
// Remix InfluencerAgreement.TokenVars(18, InfluencerAgreement.TokenOption.NONE, 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0xd04647B7CB523bb9f26730E9B6dE1174db7591Ad)
function newInfluencerAgreement(address payable _brand, address payable _influencer, uint256 _endDateTime, uint256 _payPerView, uint256 _budget,
string memory _fileHash, InfluencerAgreement.TokenVars memory _tokenVars) external payable returns(address) {
//require brand must be different than influencer
require(_brand != _influencer, 'Brand cannot = influencer');
//require budget equals money sent to contract
require(_budget == msg.value, "budget must = msg.value");
//require budget is greater than or equal to the pay per view amount
require(_budget >= _payPerView, "budget must be >= ppv");
//require end date is not in past
require(_endDateTime >= now, "end date >= now");
//create new Influencer Agreement
InfluencerAgreement a = new InfluencerAgreement {
value: _budget
}(_brand, _influencer, _endDateTime, _payPerView, _budget, _fileHash, chainlinkVars, _tokenVars);
//store new agreement in array of agreements
influencerAgreements.push(a);
// emit influencer agreement created event
emit influencerAgreementCreated(address(a));
//now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request (submit one Youtube Media ID)
// Let the influencer contract request as much link as it needs
chainlinkVars.link.approve(address(a), chainlinkVars.link.balanceOf(address(this)));
return address(a);
}
//remix newInfluencerAgreement
// function newInfluencerAgreement() external payable returns(address) {
// address payable _brand = 0x181af5Fc47b5c276BE283B40AFD5A1b0219e8312;
// address payable _influencer = 0xCDa3D794F33aDAccEe25d3CDA26977927377e4b4;
// uint256 _endDateTime = now + 360;
// uint256 _payPerView = 1;
// uint256 _budget = 100;
// string memory _fileHash = "";
// InfluencerAgreement.TokenVars memory _tokenVars = InfluencerAgreement.TokenVars(18, InfluencerAgreement.TokenOption.NONE, IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa), IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), AggregatorV3Interface(0xd04647B7CB523bb9f26730E9B6dE1174db7591Ad));
// //require brand must be different than influencer
// require(_brand != _influencer, 'Brand cannot = influencer');
// //require budget equals money sent to contract
// require(_budget == msg.value, "budget must = msg.value");
// //require budget is greater than or equal to the pay per view amount
// require(_budget >= _payPerView, "budget must be >= ppv");
// //require end date is not in past
// require(_endDateTime >= now, "end date >= now");
// //create new Influencer Agreement
// InfluencerAgreement a = new InfluencerAgreement {
// value: _budget
// }(_brand, _influencer, _endDateTime, _payPerView, _budget, _fileHash, chainlinkVars, _tokenVars);
// //store new agreement in array of agreements
// influencerAgreements.push(a);
// // emit influencer agreement created event
// emit influencerAgreementCreated(address(a));
// //now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request (submit one Youtube Media ID)
// // Let the influencer contract request as much link as it needs
// chainlinkVars.link.approve(address(a), chainlinkVars.link.balanceOf(address(this)));
// return address(a);
// }
/**
* @dev Return all influencer contract addresses
*/
function getInfluencerContracts() external view returns(InfluencerAgreement[] memory) {
return influencerAgreements;
}
/**
* @dev Return a particular Influencer Contract based on a influencer contract address
* Returns (addess brand, address influencer, int endDate, int budget, int payPerView, enum agreementStatus, int viewCount, int accumulatedPay, enum tokenOption, string mediaLink, string fileHash)
*/
function getInfluencerContract(address _influencerContract) external view returns(address, address, uint256, uint256, uint256, InfluencerAgreement.Status,
uint256, uint256, InfluencerAgreement.TokenOption, string memory, string memory) {
//loop through list of contracts, and find any belonging to the address
for (uint256 i = 0; i < influencerAgreements.length; i++) {
if (address(influencerAgreements[i]) == _influencerContract) {
return influencerAgreements[i].getAgreementDetails();
}
}
}
/**
* @dev Return a list of influencer contract addresses belonging to a particular brand or influencer
* _owner = 0 means influencer, 1 = brand
*/
function getInfluencerContracts(uint256 _owner, address _address) external view returns(address[] memory) {
//loop through list of contracts, and find any belonging to the address & type (influencer or brand)
//_owner variable determines if were searching for agreements for the brand or influencer
//0 = influencer & 1 = brand
uint256 finalResultCount = 0;
//because we need to know exact size of final memory array, first we need to iterate and count how many will be in the final result
for (uint256 i = 0; i < influencerAgreements.length; i++) {
if (_owner == 1) { //brand scenario
if (influencerAgreements[i].getBrand() == _address) {
finalResultCount = finalResultCount + 1;
}
} else { //influencer scenario
if (influencerAgreements[i].getInfluencer() == _address) {
finalResultCount = finalResultCount + 1;
}
}
}
//now we have the total count, we can create a memory array with the right size and then populate it
address[] memory addresses = new address[](finalResultCount);
uint256 addrCountInserted = 0;
for (uint256 j = 0; j < influencerAgreements.length; j++) {
if (_owner == 1) { //brand scenario
if (influencerAgreements[j].getBrand() == _address) {
addresses[addrCountInserted] = address(influencerAgreements[j]);
addrCountInserted = addrCountInserted + 1;
}
} else { //influencer scenario
if (influencerAgreements[j].getInfluencer() == _address) {
addresses[addrCountInserted] = address(influencerAgreements[j]);
addrCountInserted = addrCountInserted + 1;
}
}
}
return addresses;
}
/**
* @dev Emergancy termination sending all contracts funds back to contract creator
*/
function emergencyTermination() external onlyOwner() {
platformWallet.call.value(address(this).balance)("");
require(chainlinkVars.link.transfer(platformWallet, chainlinkVars.link.balanceOf(address(this))), "Unable to transfer");
}
/**
* @dev helper function to turn string to bytes32
*/
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
/**
* @dev receive Ether function
*/
receive() external payable {}
}
contract InfluencerAgreement is ChainlinkClient, Ownable {
using SafeMathChainlink
for uint256;
// Agreement status
enum Status {
PROPOSED,
REJECTED,
ACTIVE,
COMPLETED,
ENDED_ERROR
}
Status private agreementStatus;
// currencies agreement can store funds in
enum TokenOption {
NONE,
USDT,
USDC,
DAI
}
//token variables to work with agreement's funds
struct TokenVars {
uint128 tokenDecimals;
TokenOption tokenOption;
IERC20 TOKEN;
IUniswapV2Router02 uniswapRouter;
AggregatorV3Interface priceFeed;
}
TokenVars private tokenVars;
//chainlink variables
InfluencerAgreementFactory.ChainlinkVars private chainlinkVars;
// contract variables
address payable private dappWallet = msg.sender; //influencer agreement factory address
address payable private brand;
address payable private influencer;
uint256 private endDateTime;
uint256 private payPerView;
uint256 private budget;
string private mediaLink;
string private fileHash;
string private API_KEY = "&key=AIzaSyB8UEknqf0DmdJW5Ow6rGP8co7I_dZEhwo";
string private BASE_URL = "https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=";
//variables for calulating final
uint256 private viewCount; //how many views their content's gathered
uint256 private accumulatedPay; //how much they've already withdrawn
uint256 constant private PLATFORM_FEE = 1; //What percentage of the withdrawn amount goes to the Platform.
//List of events
event influencerAgreementCreated(Status agreementStatus);
event influencerAgreementAccepted(string mediaLink);
event influencerPaid(address influencer, uint256 amount);
/**
* @dev Modifier to check if the brand is calling the transaction
*/
modifier onlyBrand() {
require(brand == msg.sender, 'Must be Brand');
_;
}
/**
* @dev Modifier to check if the influncer is calling the transaction
*/
modifier onlyInfluencer() {
require(influencer == msg.sender, 'Must be Influencer');
_;
}
/**
* @dev Prevents a function being run unless contract is proposed
*/
modifier onlyContractProposed() {
require(agreementStatus == Status.PROPOSED, 'Contract must be PROPOSED');
_;
}
/**
* @dev Prevents a function being run unless contract is still active
*/
modifier onlyContractActive() {
require(agreementStatus == Status.ACTIVE, 'Contract must be ACTIVE');
_;
}
/**
* @dev Prevents a function being run unless contract is proposed or still active
*/
modifier onlyContractProposedOrActive() {
require(agreementStatus == Status.PROPOSED || agreementStatus == Status.ACTIVE, 'Contract must be PROPOSED or ACTIVE');
_;
}
/**
* @dev Step 01: Generate a contract in PROPOSED status
* params(address brand, address influencer, int endDate, int payPerView, int budget, string fileHash, struct chainlinkVars{bytes32 bytes32JobId, bytes32 uintJobId, address oracle, address link, int oraclePayment}, struct tokenInitVars{int tokenDecimals, TokenOption tokenOption(NONE, USDT, USDC, DAI), address tokenAddress, address uniswapRouter, address tokenPriceFeed}){value: budget}
*/
constructor(
address payable _brand, address payable _influencer, uint256 _endDateTime, uint256 _payPerView, uint256 _budget, string memory _fileHash, InfluencerAgreementFactory.ChainlinkVars memory _chainlinkVars,
TokenVars memory _tokenVars
) payable Ownable() public {
// initialize variables required for Chainlink Node interaction
chainlinkVars = _chainlinkVars;
setChainlinkToken(address(chainlinkVars.link));
setChainlinkOracle(chainlinkVars.oracle);
// now initialize values for the contract
brand = _brand;
influencer = _influencer;
endDateTime = _endDateTime;
budget = _budget;
payPerView = _payPerView;
agreementStatus = Status.PROPOSED;
fileHash = _fileHash;
// now initialize values for the token and convert contract's eth to token
tokenVars = _tokenVars;
convertEthToToken(budget);
emit influencerAgreementCreated(agreementStatus);
}
/**
* @dev Step 02a: Influencer ACCEPTS proposal, contract becomes ACTIVE
*/
function approveContract(string memory _mediaLink) external onlyInfluencer() onlyContractProposedOrActive() {
//Influencer looks at proposed agreement & either approves or denies it.
//To accept it, the influencer must upload a link to their media.
// Only influencer can run this, contract must be in PROPOSED status
mediaLink = _mediaLink;
//In this case, we approve. Contract becomes Active
agreementStatus = Status.ACTIVE;
//finally, schedule contract termination date
requestTermination(endDateTime);
emit influencerAgreementAccepted(mediaLink);
}
/**
* @dev Step 02b: Influencer REJECTS proposal, contract becomes REJECTED. This is the end of the line for the Contract
*/
function rejectContract() external onlyInfluencer() onlyContractProposed() {
//Influencer looks at proposed agreement & either approves or denies it.
//Only influencer can call this function
//In this case, we approve. Contract becomes Rejected. No more actions should be possible on the contract in this status
//return money to brand
require(tokenVars.TOKEN.transfer(brand, tokenVars.TOKEN.balanceOf(address(this))), "Unable to transfer");
//return any LINK tokens in here back to the DAPP wallet
require(chainlinkVars.link.transfer(dappWallet, chainlinkVars.link.balanceOf(address(this))), "Unable to transfer");
//Set status to rejected. This is the end of the line for this agreement
agreementStatus = Status.REJECTED;
}
/**
* @dev Step 03: Contract ends. Transfers out remaining funds to brand and dappWallet
*/
function endContract() internal {
//prevent re-entrency
uint contractFunds = tokenVars.TOKEN.balanceOf(address(this));
//Total to go to platform = base fee / platform fee %
uint totalPlatformFee = (contractFunds.mul(PLATFORM_FEE)).div(100);
//Transfer remaining balnce to brand
require(tokenVars.TOKEN.transfer(brand, contractFunds - totalPlatformFee), "Unable to transfer");
require(tokenVars.TOKEN.transfer(dappWallet, totalPlatformFee), "Unable to transfer");
//return any LINK tokens in here back to the DAPP wallet
require(chainlinkVars.link.transfer(dappWallet, chainlinkVars.link.balanceOf(address(this))), "Unable to transfer");
}
/**
* @dev Get view count on a video. Ensure its not past the contract deadline and contract is active
*/
function getViewCount() internal onlyContractActive() returns(bytes32 requestId) {
// check Link in this contract to see if we need to request more before proceeding
checkLINK();
// Get video view count
Chainlink.Request memory req = buildChainlinkRequest(chainlinkVars.bytes32JobId, address(this), this.withdrawFallback.selector);
bytes memory url_bytes = abi.encodePacked(BASE_URL, mediaLink, API_KEY);
req.add("get", string(url_bytes));
// Set the path to find the desired data in the API response, where the response format is:
// {
// "kind": "youtube#videoListResponse",
// "etag": "ZmcX3BsmhS9iLumLv4kaVxnfeZ8",
// "items": [
// {
// "kind": "youtube#video",
// "etag": "oW3as3wjv-heYr4pGVlHnmFRgKw",
// "id": "Ks-_Mh1QhMc",
// "statistics": {
// "viewCount": "19255415",
// "likeCount": "285037",
// "dislikeCount": "5512",
// "favoriteCount": "0",
// "commentCount": "8580"
// }
// }
// ],
// "pageInfo": {
// "totalResults": 1,
// "resultsPerPage": 1
// }
// }
req.add("path", "items.0.statistics.viewCount");
return sendChainlinkRequestTo(chainlinkOracleAddress(), req, chainlinkVars.oraclePayment);
}
/**
* @dev Callback function for getting the view count on a video, then transfers funds to influencer and ends contract if needed
*/
function withdrawFallback(bytes32 _requestId, bytes32 _viewCount) public recordChainlinkFulfillment(_requestId) {
//Set contract variables to start the agreement
string memory _viewCountString = bytes32ToString(_viewCount);
viewCount = uint256(parseInt(_viewCountString, 0));
//Turn string total view count into an int and calculate pay for influencer
uint256 budgetRmaining = tokenVars.TOKEN.balanceOf(address(this));
uint256 pay = (payPerView * viewCount) - accumulatedPay;
if (pay > budgetRmaining) {
pay = budgetRmaining;
}
//Total to go to platform = base fee / platform fee %
uint totalPlatformFee = (pay.mul(PLATFORM_FEE)).div(100);
// transfer and update accumulatedPay and remaining budget
require(tokenVars.TOKEN.transfer(influencer, pay - totalPlatformFee), "Unable to transfer");
require(tokenVars.TOKEN.transfer(dappWallet, totalPlatformFee), "Unable to transfer");
accumulatedPay += pay;
// emit influencer paid event
emit influencerPaid(influencer, pay);
//Now if contract completed, keep transferring out money
if (agreementStatus == Status.COMPLETED) {
endContract();
}
}
/**
* Create a Chainlink request to schedule the termination
* of this contract and make the final function calls
*
*/
function requestTermination(uint256 date) internal returns(bytes32 requestId) {
// check Link in this contract to see if we need to request more before proceeding
checkLINK();
Chainlink.Request memory req = buildChainlinkRequest(chainlinkVars.uintJobId, address(this), this.fulfillTermination.selector);
req.addUint("until", date);
return sendChainlinkRequestTo(chainlinkOracleAddress(), req, chainlinkVars.oraclePayment);
}
/**
* Receive the termnation response in the form of uint256
*/
function fulfillTermination(bytes32 _requestId) public recordChainlinkFulfillment(_requestId) {
//end contract
agreementStatus = Status.COMPLETED;
getViewCount();
}
/**
* @dev convert wei to stable coin
*/
function convertEthToToken(uint _weiAmount) internal {
uint256 deadline = block.timestamp + 15;
//uniswap required path. First element is input token, second is output token
// set input token as wei and output as token
address[] memory path = new address[](2);
path[0] = tokenVars.uniswapRouter.WETH();
path[1] = address(tokenVars.TOKEN);
// get minimum amount of stable coin we'll accept for this conversion
// ensure we don't get ripped off
uint256 amountOutMin;
uint256 tokenEthPrice = getLatestTokenEthPrice();
if (tokenVars.tokenOption == TokenOption.NONE) {
amountOutMin = _weiAmount;
} else {
amountOutMin = (_weiAmount.mul(99).mul(10**tokenVars.tokenDecimals)).div(tokenEthPrice.mul(100));
}
// swaps = The input token amount and all subsequent output token amounts.
uint256[] memory swaps = tokenVars.uniswapRouter.swapExactETHForTokens {
value: _weiAmount
}(amountOutMin, path, address(this), deadline);
// refund leftover ETH to the brand
(bool success, ) = (brand).call {
value: (address(this)).balance
}("");
require(success, "refund failed");
// set budget to token amount
budget = swaps[1];
payPerView = (payPerView.mul(10**tokenVars.tokenDecimals)).div(tokenEthPrice);
}
/**
* @dev convert stable coin to stable wei
*/
function convertTokenToEth(uint _tokenAmount) internal {
//first appprove the router to withdraw the token
require(tokenVars.TOKEN.approve(address(tokenVars.uniswapRouter), _tokenAmount), 'approve failed.');
//thencontinue as normal
uint256 deadline = block.timestamp + 15;
//uniswap required path. First element is input token, second is output token
// set input token as wei and output as token
address[] memory path = new address[](2);
path[0] = address(tokenVars.TOKEN);
path[1] = tokenVars.uniswapRouter.WETH();
// get minimum amount of wei we'll accept for this conversion
// ensure we don't get ripped off
uint256 amountOutMin;
if (tokenVars.tokenOption == TokenOption.NONE) {
amountOutMin = _tokenAmount;
} else {
amountOutMin = (_tokenAmount.mul(getLatestTokenEthPrice()).mul(99)).div(100*(10**tokenVars.tokenDecimals));
}
// swaps = The input token amount and all subsequent output token amounts.
uint256[] memory swaps = tokenVars.uniswapRouter.swapExactTokensForETH(_tokenAmount, amountOutMin, path, address(this), deadline);
}
/**
* @dev get wei/token. eg. returns 353420000000000 wei per tether
*/
function getLatestTokenEthPrice() internal view returns(uint256) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = tokenVars.priceFeed.latestRoundData();
// If the round is not complete yet, timestamp is 0
require(timeStamp > 0, "Round not complete");
return uint256(price);
}
/**
* @dev withdraw money
*/
function withdraw() external onlyInfluencer() {
// call getViewCount() transfer funds to influencer
getViewCount();
}
/**
* @dev Checks how much LINK is in the contract and requests more from the factory if necessary. Returns link remaining at the end.
* Only this contrac can call it
*/
function checkLINK() internal returns(uint256) {
uint256 linkRemaining = chainlinkVars.link.balanceOf(address(this));
// Request another LINK token if the contract's remaining link gets too low
if (linkRemaining < 1 ether) {
require(chainlinkVars.link.transferFrom(dappWallet, address(this), 1 ether), "Unable to transfer");
}
return (chainlinkVars.link.balanceOf(address(this)));
}
/**
* @dev Get address of the chainlink token
*/
function getChainlinkToken() public view returns(address) {
return chainlinkTokenAddress();
}
/**
* @dev Return All Details about a Influencer Agreement
* Returns (addess brand, address influencer, int endDate, int budget, int payPerView, enum agreementStatus, int viewCount, int accumulatedPay, enum tokenOption, string mediaLink, string fileHash)
*/
function getAgreementDetails() external view returns(address, address, uint256, uint256, uint256, Status,
uint256, uint256, TokenOption, string memory, string memory) {
return (brand, influencer, endDateTime, budget, payPerView, agreementStatus, viewCount, accumulatedPay, tokenVars.tokenOption, mediaLink, fileHash);
}
/**
* @dev Get brand address
*/
function getBrand() external view returns(address) {
return brand;
}
/**
* @dev Get influencer address
*/
function getInfluencer() external view returns(address) {
return influencer;
}
/**
* @dev Emergancy termination sending all contracts funds back to contract creator
*/
function emergencyTermination() external onlyOwner() {
// transfer link
require(chainlinkVars.link.transfer(dappWallet, chainlinkVars.link.balanceOf(address(this))), "Unable to transfer");
// convert token to eth and transfer
convertTokenToEth(tokenVars.TOKEN.balanceOf(address(this)));
dappWallet.call.value(address(this).balance)("");
}
/**
* @dev converts bytes32 to string
*/
function bytes32ToString(bytes32 _bytes32) internal pure returns(string memory) {
uint256 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
/**
* @dev converts a string to an int. _b is the power of 10 to multiply it by.
*/
function parseInt(string memory _a, uint _b) internal pure returns(int) {
bytes memory bresult = bytes(_a);
int mint = 0;
bool decimals = false;
bool negative = false;
for (uint i = 0; i < bresult.length; i++) {
if ((i == 0) && (bresult[i] == '-')) {
negative = true;
}
if ((uint8(bresult[i]) >= 48) && (uint8(bresult[i]) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint8(bresult[i]) - 48;
} else if (uint8(bresult[i]) == 46) decimals = true;
}
if (_b > 0) mint *= int(10 ** _b);
if (negative) mint *= -1;
return mint;
}
/**
* @dev fallback function
*/
receive() payable external {}
} | Return All Details about a Influencer Agreement Returns (addess brand, address influencer, int endDate, int budget, int payPerView, enum agreementStatus, int viewCount, int accumulatedPay, enum tokenOption, string mediaLink, string fileHash)/ | function getAgreementDetails() external view returns(address, address, uint256, uint256, uint256, Status,
uint256, uint256, TokenOption, string memory, string memory) {
return (brand, influencer, endDateTime, budget, payPerView, agreementStatus, viewCount, accumulatedPay, tokenVars.tokenOption, mediaLink, fileHash);
}
| 6,399,076 |
./full_match/1/0xd7C0f19C4dB13F076802AEc732956eedBBafc370/sources/contracts/Dependencies/LiquityMath.sol | _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. Called by one function that represent time in units of minutes: 1) TroveManager._calcDecayedBaseRate The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals "minutes in 1000 years": 60 24 365 1000 If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be negligibly different from just passing the cap, since: In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible/ Exponentiation-by-squaring | function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint) {
uint256 y = DECIMAL_PRECISION;
uint256 x = _base;
uint256 n = _minutes;
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n / 2;
y = decMul(x, y);
x = decMul(x, x);
n = (n - 1) / 2;
}
}
return decMul(x, y);
}
| 4,892,501 |
/**
*Submitted for verification at Etherscan.io on 2021-05-25
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/src/common/libs/Decimals.sol
pragma solidity 0.5.17;
/**
* Library for emulating calculations involving decimals.
*/
library Decimals {
using SafeMath for uint256;
uint120 private constant BASIS_VAKUE = 1000000000000000000;
/**
* @dev Returns the ratio of the first argument to the second argument.
* @param _a Numerator.
* @param _b Fraction.
* @return Calculated ratio.
*/
function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(BASIS_VAKUE);
if (a < _b) {
return 0;
}
return (a.div(_b));
}
/**
* @dev Returns multiplied the number by 10^18.
* @param _a Numerical value to be multiplied.
* @return Multiplied value.
*/
function mulBasis(uint256 _a) internal pure returns (uint256) {
return _a.mul(BASIS_VAKUE);
}
/**
* @dev Returns divisioned the number by 10^18.
* This function can use it to restore the number of digits in the result of `outOf`.
* @param _a Numerical value to be divisioned.
* @return Divisioned value.
*/
function divBasis(uint256 _a) internal pure returns (uint256) {
return _a.div(BASIS_VAKUE);
}
}
// File: contracts/interface/IAddressConfig.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IAddressConfig {
function token() external view returns (address);
function allocator() external view returns (address);
function allocatorStorage() external view returns (address);
function withdraw() external view returns (address);
function withdrawStorage() external view returns (address);
function marketFactory() external view returns (address);
function marketGroup() external view returns (address);
function propertyFactory() external view returns (address);
function propertyGroup() external view returns (address);
function metricsGroup() external view returns (address);
function metricsFactory() external view returns (address);
function policy() external view returns (address);
function policyFactory() external view returns (address);
function policySet() external view returns (address);
function policyGroup() external view returns (address);
function lockup() external view returns (address);
function lockupStorage() external view returns (address);
function voteTimes() external view returns (address);
function voteTimesStorage() external view returns (address);
function voteCounter() external view returns (address);
function voteCounterStorage() external view returns (address);
function setAllocator(address _addr) external;
function setAllocatorStorage(address _addr) external;
function setWithdraw(address _addr) external;
function setWithdrawStorage(address _addr) external;
function setMarketFactory(address _addr) external;
function setMarketGroup(address _addr) external;
function setPropertyFactory(address _addr) external;
function setPropertyGroup(address _addr) external;
function setMetricsFactory(address _addr) external;
function setMetricsGroup(address _addr) external;
function setPolicyFactory(address _addr) external;
function setPolicyGroup(address _addr) external;
function setPolicySet(address _addr) external;
function setPolicy(address _addr) external;
function setToken(address _addr) external;
function setLockup(address _addr) external;
function setLockupStorage(address _addr) external;
function setVoteTimes(address _addr) external;
function setVoteTimesStorage(address _addr) external;
function setVoteCounter(address _addr) external;
function setVoteCounterStorage(address _addr) external;
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity 0.5.17;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
address private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = _addressConfig;
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (IAddressConfig) {
return IAddressConfig(_config);
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return _config;
}
}
// File: contracts/interface/IUsingStorage.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IUsingStorage {
function getStorageAddress() external view returns (address);
function createStorage() external;
function setStorage(address _storageAddress) external;
function changeOwner(address newOwner) external;
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity 0.5.17;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity 0.5.17;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable, IUsingStorage {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/lockup/LockupStorage.sol
pragma solidity 0.5.17;
contract LockupStorage is UsingStorage {
using SafeMath for uint256;
uint256 private constant BASIS = 100000000000000000000000000000000;
//AllValue
function setStorageAllValue(uint256 _value) internal {
bytes32 key = getStorageAllValueKey();
eternalStorage().setUint(key, _value);
}
function getStorageAllValue() public view returns (uint256) {
bytes32 key = getStorageAllValueKey();
return eternalStorage().getUint(key);
}
function getStorageAllValueKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_allValue"));
}
//Value
function setStorageValue(
address _property,
address _sender,
uint256 _value
) internal {
bytes32 key = getStorageValueKey(_property, _sender);
eternalStorage().setUint(key, _value);
}
function getStorageValue(address _property, address _sender)
public
view
returns (uint256)
{
bytes32 key = getStorageValueKey(_property, _sender);
return eternalStorage().getUint(key);
}
function getStorageValueKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_value", _property, _sender));
}
//PropertyValue
function setStoragePropertyValue(address _property, uint256 _value)
internal
{
bytes32 key = getStoragePropertyValueKey(_property);
eternalStorage().setUint(key, _value);
}
function getStoragePropertyValue(address _property)
public
view
returns (uint256)
{
bytes32 key = getStoragePropertyValueKey(_property);
return eternalStorage().getUint(key);
}
function getStoragePropertyValueKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_propertyValue", _property));
}
//InterestPrice
function setStorageInterestPrice(address _property, uint256 _value)
internal
{
// The previously used function
// This function is only used in testing
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
}
function getStorageInterestPrice(address _property)
public
view
returns (uint256)
{
return eternalStorage().getUint(getStorageInterestPriceKey(_property));
}
function getStorageInterestPriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_interestTotals", _property));
}
//LastInterestPrice
function setStorageLastInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastInterestPriceKey(_property, _user)
);
}
function getStorageLastInterestPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastLastInterestPrice", _property, _user)
);
}
//LastSameRewardsAmountAndBlock
function setStorageLastSameRewardsAmountAndBlock(
uint256 _amount,
uint256 _block
) internal {
uint256 record = _amount.mul(BASIS).add(_block);
eternalStorage().setUint(
getStorageLastSameRewardsAmountAndBlockKey(),
record
);
}
function getStorageLastSameRewardsAmountAndBlock()
public
view
returns (uint256 _amount, uint256 _block)
{
uint256 record =
eternalStorage().getUint(
getStorageLastSameRewardsAmountAndBlockKey()
);
uint256 amount = record.div(BASIS);
uint256 blockNumber = record.sub(amount.mul(BASIS));
return (amount, blockNumber);
}
function getStorageLastSameRewardsAmountAndBlockKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock"));
}
//CumulativeGlobalRewards
function setStorageCumulativeGlobalRewards(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeGlobalRewardsKey(),
_value
);
}
function getStorageCumulativeGlobalRewards() public view returns (uint256) {
return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey());
}
function getStorageCumulativeGlobalRewardsKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeGlobalRewards"));
}
//PendingWithdrawal
function setStoragePendingInterestWithdrawal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStoragePendingInterestWithdrawalKey(_property, _user),
_value
);
}
function getStoragePendingInterestWithdrawal(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStoragePendingInterestWithdrawalKey(_property, _user)
);
}
function getStoragePendingInterestWithdrawalKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_pendingInterestWithdrawal", _property, _user)
);
}
//DIP4GenesisBlock
function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
function getStorageDIP4GenesisBlock() public view returns (uint256) {
return eternalStorage().getUint(getStorageDIP4GenesisBlockKey());
}
function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_dip4GenesisBlock"));
}
//lastStakedInterestPrice
function setStorageLastStakedInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastStakedInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastStakedInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastStakedInterestPriceKey(_property, _user)
);
}
function getStorageLastStakedInterestPriceKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_lastStakedInterestPrice", _property, _user)
);
}
//lastStakesChangedCumulativeReward
function setStorageLastStakesChangedCumulativeReward(uint256 _value)
internal
{
eternalStorage().setUint(
getStorageLastStakesChangedCumulativeRewardKey(),
_value
);
}
function getStorageLastStakesChangedCumulativeReward()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastStakesChangedCumulativeRewardKey()
);
}
function getStorageLastStakesChangedCumulativeRewardKey()
private
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("_lastStakesChangedCumulativeReward"));
}
//LastCumulativeHoldersRewardPrice
function setStorageLastCumulativeHoldersRewardPrice(uint256 _holders)
internal
{
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPriceKey(),
_holders
);
}
function getStorageLastCumulativeHoldersRewardPrice()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardPriceKey()
);
}
function getStorageLastCumulativeHoldersRewardPriceKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("0lastCumulativeHoldersRewardPrice"));
}
//LastCumulativeInterestPrice
function setStorageLastCumulativeInterestPrice(uint256 _interest) internal {
eternalStorage().setUint(
getStorageLastCumulativeInterestPriceKey(),
_interest
);
}
function getStorageLastCumulativeInterestPrice()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeInterestPriceKey()
);
}
function getStorageLastCumulativeInterestPriceKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("0lastCumulativeInterestPrice"));
}
//LastCumulativeHoldersRewardAmountPerProperty
function setStorageLastCumulativeHoldersRewardAmountPerProperty(
address _property,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
_property
),
_value
);
}
function getStorageLastCumulativeHoldersRewardAmountPerProperty(
address _property
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
_property
)
);
}
function getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
address _property
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"0lastCumulativeHoldersRewardAmountPerProperty",
_property
)
);
}
//LastCumulativeHoldersRewardPricePerProperty
function setStorageLastCumulativeHoldersRewardPricePerProperty(
address _property,
uint256 _price
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property),
_price
);
}
function getStorageLastCumulativeHoldersRewardPricePerProperty(
address _property
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(
_property
)
);
}
function getStorageLastCumulativeHoldersRewardPricePerPropertyKey(
address _property
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"0lastCumulativeHoldersRewardPricePerProperty",
_property
)
);
}
//cap
function setStorageCap(uint256 _cap) internal {
eternalStorage().setUint(getStorageCapKey(), _cap);
}
function getStorageCap() public view returns (uint256) {
return eternalStorage().getUint(getStorageCapKey());
}
function getStorageCapKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_cap"));
}
//CumulativeHoldersRewardCap
function setStorageCumulativeHoldersRewardCap(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeHoldersRewardCapKey(),
_value
);
}
function getStorageCumulativeHoldersRewardCap()
public
view
returns (uint256)
{
return
eternalStorage().getUint(getStorageCumulativeHoldersRewardCapKey());
}
function getStorageCumulativeHoldersRewardCapKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeHoldersRewardCap"));
}
//LastCumulativeHoldersPriceCap
function setStorageLastCumulativeHoldersPriceCap(uint256 _value) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersPriceCapKey(),
_value
);
}
function getStorageLastCumulativeHoldersPriceCap()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersPriceCapKey()
);
}
function getStorageLastCumulativeHoldersPriceCapKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_lastCumulativeHoldersPriceCap"));
}
//InitialCumulativeHoldersRewardCap
function setStorageInitialCumulativeHoldersRewardCap(
address _property,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageInitialCumulativeHoldersRewardCapKey(_property),
_value
);
}
function getStorageInitialCumulativeHoldersRewardCap(address _property)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageInitialCumulativeHoldersRewardCapKey(_property)
);
}
function getStorageInitialCumulativeHoldersRewardCapKey(address _property)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"_initialCumulativeHoldersRewardCap",
_property
)
);
}
//FallbackInitialCumulativeHoldersRewardCap
function setStorageFallbackInitialCumulativeHoldersRewardCap(uint256 _value)
internal
{
eternalStorage().setUint(
getStorageFallbackInitialCumulativeHoldersRewardCapKey(),
_value
);
}
function getStorageFallbackInitialCumulativeHoldersRewardCap()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageFallbackInitialCumulativeHoldersRewardCapKey()
);
}
function getStorageFallbackInitialCumulativeHoldersRewardCapKey()
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_fallbackInitialCumulativeHoldersRewardCap")
);
}
}
// File: contracts/interface/IDevMinter.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IDevMinter {
function mint(address account, uint256 amount) external returns (bool);
function renounceMinter() external;
}
// File: contracts/interface/IProperty.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IProperty {
function author() external view returns (address);
function changeAuthor(address _nextAuthor) external;
function changeName(string calldata _name) external;
function changeSymbol(string calldata _symbol) external;
function withdraw(address _sender, uint256 _value) external;
}
// File: contracts/interface/IPolicy.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IPolicy {
function rewards(uint256 _lockups, uint256 _assets)
external
view
returns (uint256);
function holdersShare(uint256 _amount, uint256 _lockups)
external
view
returns (uint256);
function authenticationFee(uint256 _assets, uint256 _propertyAssets)
external
view
returns (uint256);
function marketApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function policyApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function marketVotingBlocks() external view returns (uint256);
function policyVotingBlocks() external view returns (uint256);
function shareOfTreasury(uint256 _supply) external view returns (uint256);
function treasury() external view returns (address);
function capSetter() external view returns (address);
}
// File: contracts/interface/IAllocator.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IAllocator {
function beforeBalanceChange(
address _property,
address _from,
address _to
) external;
function calculateMaxRewardsPerBlock() external view returns (uint256);
}
// File: contracts/interface/ILockup.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface ILockup {
function lockup(
address _from,
address _property,
uint256 _value
) external;
function update() external;
function withdraw(address _property, uint256 _amount) external;
function calculateCumulativeRewardPrices()
external
view
returns (
uint256 _reward,
uint256 _holders,
uint256 _interest,
uint256 _holdersCap
);
function calculateRewardAmount(address _property)
external
view
returns (uint256, uint256);
/**
* caution!!!this function is deprecated!!!
* use calculateRewardAmount
*/
function calculateCumulativeHoldersRewardAmount(address _property)
external
view
returns (uint256);
function getPropertyValue(address _property)
external
view
returns (uint256);
function getAllValue() external view returns (uint256);
function getValue(address _property, address _sender)
external
view
returns (uint256);
function calculateWithdrawableInterestAmount(
address _property,
address _user
) external view returns (uint256);
function cap() external view returns (uint256);
function updateCap(uint256 _cap) external;
function devMinter() external view returns (address);
}
// File: contracts/interface/IMetricsGroup.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IMetricsGroup {
function addGroup(address _addr) external;
function removeGroup(address _addr) external;
function isGroup(address _addr) external view returns (bool);
function totalIssuedMetrics() external view returns (uint256);
function hasAssets(address _property) external view returns (bool);
function getMetricsCountPerProperty(address _property)
external
view
returns (uint256);
function totalAuthenticatedProperties() external view returns (uint256);
// deplicated!!!!!!!
function setTotalAuthenticatedPropertiesAdmin(uint256 _value) external;
}
// File: contracts/src/lockup/Lockup.sol
pragma solidity 0.5.17;
// prettier-ignore
/**
* A contract that manages the staking of DEV tokens and calculates rewards.
* Staking and the following mechanism determines that reward calculation.
*
* Variables:
* -`M`: Maximum mint amount per block determined by Allocator contract
* -`B`: Number of blocks during staking
* -`P`: Total number of staking locked up in a Property contract
* -`S`: Total number of staking locked up in all Property contracts
* -`U`: Number of staking per account locked up in a Property contract
*
* Formula:
* Staking Rewards = M * B * (P / S) * (U / P)
*
* Note:
* -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted.
* -`B` is added every time the Ethereum block is created.
* - Only `U` and `B` are predictable variables.
* - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history.
* - Reward withdrawal always withdraws the total withdrawable amount.
*
* Scenario:
* - Assume `M` is fixed at 500
* - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100)
* - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100)
* - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100)
* - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV).
*/
contract Lockup is ILockup, UsingConfig, LockupStorage {
using SafeMath for uint256;
using Decimals for uint256;
address public devMinter;
struct RewardPrices {
uint256 reward;
uint256 holders;
uint256 interest;
uint256 holdersCap;
}
event Lockedup(address _from, address _property, uint256 _value);
/**
* Initialize the passed address as AddressConfig address and Devminter.
*/
constructor(address _config, address _devMinter)
public
UsingConfig(_config)
{
devMinter = _devMinter;
}
/**
* Adds staking.
* Only the Dev contract can execute this function.
*/
function lockup(
address _from,
address _property,
uint256 _value
) external {
/**
* Validates the sender is Dev contract.
*/
require(msg.sender == config().token(), "this is illegal address");
/**
* Validates _value is not 0.
*/
require(_value != 0, "illegal lockup value");
/**
* Validates the passed Property has greater than 1 asset.
*/
require(
IMetricsGroup(config().metricsGroup()).hasAssets(_property),
"unable to stake to unauthenticated property"
);
/**
* Since the reward per block that can be withdrawn will change with the addition of staking,
* saves the undrawn withdrawable reward before addition it.
*/
RewardPrices memory prices =
updatePendingInterestWithdrawal(_property, _from);
/**
* Saves variables that should change due to the addition of staking.
*/
updateValues(true, _from, _property, _value, prices);
emit Lockedup(_from, _property, _value);
}
/**
* Withdraw staking.
* Releases staking, withdraw rewards, and transfer the staked and withdraw rewards amount to the sender.
*/
function withdraw(address _property, uint256 _amount) external {
/**
* Validates the sender is staking to the target Property.
*/
require(
hasValue(_property, msg.sender, _amount),
"insufficient tokens staked"
);
/**
* Withdraws the staking reward
*/
RewardPrices memory prices = _withdrawInterest(_property);
/**
* Transfer the staked amount to the sender.
*/
if (_amount != 0) {
IProperty(_property).withdraw(msg.sender, _amount);
}
/**
* Saves variables that should change due to the canceling staking..
*/
updateValues(false, msg.sender, _property, _amount, prices);
}
/**
* get cap
*/
function cap() external view returns (uint256) {
return getStorageCap();
}
/**
* set cap
*/
function updateCap(uint256 _cap) external {
address setter = IPolicy(config().policy()).capSetter();
require(setter == msg.sender, "illegal access");
/**
* Updates cumulative amount of the holders reward cap
*/
(, uint256 holdersPrice, , uint256 cCap) =
calculateCumulativeRewardPrices();
// TODO: When this function is improved to be called on-chain, the source of `getStorageLastCumulativeHoldersPriceCap` can be rewritten to `getStorageLastCumulativeHoldersRewardPrice`.
setStorageCumulativeHoldersRewardCap(cCap);
setStorageLastCumulativeHoldersPriceCap(holdersPrice);
setStorageCap(_cap);
}
/**
* Returns the latest cap
*/
function _calculateLatestCap(uint256 _holdersPrice)
private
view
returns (uint256)
{
uint256 cCap = getStorageCumulativeHoldersRewardCap();
uint256 lastHoldersPrice = getStorageLastCumulativeHoldersPriceCap();
uint256 additionalCap =
_holdersPrice.sub(lastHoldersPrice).mul(getStorageCap());
return cCap.add(additionalCap);
}
/**
* Store staking states as a snapshot.
*/
function beforeStakesChanged(
address _property,
address _user,
RewardPrices memory _prices
) private {
/**
* Gets latest cumulative holders reward for the passed Property.
*/
uint256 cHoldersReward =
_calculateCumulativeHoldersRewardAmount(_prices.holders, _property);
/**
* Sets `InitialCumulativeHoldersRewardCap`.
* Records this value only when the "first staking to the passed Property" is transacted.
*/
if (
getStorageLastCumulativeHoldersRewardPricePerProperty(_property) ==
0 &&
getStorageInitialCumulativeHoldersRewardCap(_property) == 0 &&
getStoragePropertyValue(_property) == 0
) {
setStorageInitialCumulativeHoldersRewardCap(
_property,
_prices.holdersCap
);
}
/**
* Store each value.
*/
setStorageLastStakedInterestPrice(_property, _user, _prices.interest);
setStorageLastStakesChangedCumulativeReward(_prices.reward);
setStorageLastCumulativeHoldersRewardPrice(_prices.holders);
setStorageLastCumulativeInterestPrice(_prices.interest);
setStorageLastCumulativeHoldersRewardAmountPerProperty(
_property,
cHoldersReward
);
setStorageLastCumulativeHoldersRewardPricePerProperty(
_property,
_prices.holders
);
setStorageCumulativeHoldersRewardCap(_prices.holdersCap);
setStorageLastCumulativeHoldersPriceCap(_prices.holders);
}
/**
* Gets latest value of cumulative sum of the reward amount, cumulative sum of the holders reward per stake, and cumulative sum of the stakers reward per stake.
*/
function calculateCumulativeRewardPrices()
public
view
returns (
uint256 _reward,
uint256 _holders,
uint256 _interest,
uint256 _holdersCap
)
{
uint256 lastReward = getStorageLastStakesChangedCumulativeReward();
uint256 lastHoldersPrice = getStorageLastCumulativeHoldersRewardPrice();
uint256 lastInterestPrice = getStorageLastCumulativeInterestPrice();
uint256 allStakes = getStorageAllValue();
/**
* Gets latest cumulative sum of the reward amount.
*/
(uint256 reward, ) = dry();
uint256 mReward = reward.mulBasis();
/**
* Calculates reward unit price per staking.
* Later, the last cumulative sum of the reward amount is subtracted because to add the last recorded holder/staking reward.
*/
uint256 price =
allStakes > 0 ? mReward.sub(lastReward).div(allStakes) : 0;
/**
* Calculates the holders reward out of the total reward amount.
*/
uint256 holdersShare =
IPolicy(config().policy()).holdersShare(price, allStakes);
/**
* Calculates and returns each reward.
*/
uint256 holdersPrice = holdersShare.add(lastHoldersPrice);
uint256 interestPrice = price.sub(holdersShare).add(lastInterestPrice);
uint256 cCap = _calculateLatestCap(holdersPrice);
return (mReward, holdersPrice, interestPrice, cCap);
}
/**
* Calculates cumulative sum of the holders reward per Property.
* To save computing resources, it receives the latest holder rewards from a caller.
*/
function _calculateCumulativeHoldersRewardAmount(
uint256 _holdersPrice,
address _property
) private view returns (uint256) {
(uint256 cHoldersReward, uint256 lastReward) =
(
getStorageLastCumulativeHoldersRewardAmountPerProperty(
_property
),
getStorageLastCumulativeHoldersRewardPricePerProperty(_property)
);
/**
* `cHoldersReward` contains the calculation of `lastReward`, so subtract it here.
*/
uint256 additionalHoldersReward =
_holdersPrice.sub(lastReward).mul(
getStoragePropertyValue(_property)
);
/**
* Calculates and returns the cumulative sum of the holder reward by adds the last recorded holder reward and the latest holder reward.
*/
return cHoldersReward.add(additionalHoldersReward);
}
/**
* Calculates cumulative sum of the holders reward per Property.
* caution!!!this function is deprecated!!!
* use calculateRewardAmount
*/
function calculateCumulativeHoldersRewardAmount(address _property)
external
view
returns (uint256)
{
(, uint256 holders, , ) = calculateCumulativeRewardPrices();
return _calculateCumulativeHoldersRewardAmount(holders, _property);
}
/**
* Calculates holders reward and cap per Property.
*/
function calculateRewardAmount(address _property)
external
view
returns (uint256, uint256)
{
(, uint256 holders, , uint256 holdersCap) =
calculateCumulativeRewardPrices();
uint256 initialCap = _getInitialCap(_property);
/**
* Calculates the cap
*/
uint256 capValue = holdersCap.sub(initialCap);
return (
_calculateCumulativeHoldersRewardAmount(holders, _property),
capValue
);
}
function _getInitialCap(address _property) private view returns (uint256) {
uint256 initialCap =
getStorageInitialCumulativeHoldersRewardCap(_property);
if (initialCap > 0) {
return initialCap;
}
// Fallback when there is a data past staked.
if (
getStorageLastCumulativeHoldersRewardPricePerProperty(_property) >
0 ||
getStoragePropertyValue(_property) > 0
) {
return getStorageFallbackInitialCumulativeHoldersRewardCap();
}
return 0;
}
/**
* Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block,
* and the last recorded block number.
* The cumulative sum of the maximum mint amount is always added.
* By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated.
*/
function update() public {
/**
* Gets the cumulative sum of the maximum mint amount and the maximum mint number per block.
*/
(uint256 _nextRewards, uint256 _amount) = dry();
/**
* Records each value and the latest block number.
*/
setStorageCumulativeGlobalRewards(_nextRewards);
setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
}
/**
* Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block.
*/
function dry()
private
view
returns (uint256 _nextRewards, uint256 _amount)
{
/**
* Gets the latest mint amount per block from Allocator contract.
*/
uint256 rewardsAmount =
IAllocator(config().allocator()).calculateMaxRewardsPerBlock();
/**
* Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage.
*/
(uint256 lastAmount, uint256 lastBlock) =
getStorageLastSameRewardsAmountAndBlock();
/**
* If the recorded maximum mint amount per block and the result of the Allocator contract are different,
* the result of the Allocator contract takes precedence as a maximum mint amount per block.
*/
uint256 lastMaxRewards =
lastAmount == rewardsAmount ? rewardsAmount : lastAmount;
/**
* Calculates the difference between the latest block number and the last recorded block number.
*/
uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0;
/**
* Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount.
*/
uint256 additionalRewards = lastMaxRewards.mul(blocks);
uint256 nextRewards =
getStorageCumulativeGlobalRewards().add(additionalRewards);
/**
* Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block.
*/
return (nextRewards, rewardsAmount);
}
/**
* Returns the staker reward as interest.
*/
function _calculateInterestAmount(address _property, address _user)
private
view
returns (
uint256 _amount,
uint256 _interestPrice,
RewardPrices memory _prices
)
{
/**
* Get the amount the user is staking for the Property.
*/
uint256 lockedUpPerAccount = getStorageValue(_property, _user);
/**
* Gets the cumulative sum of the interest price recorded the last time you withdrew.
*/
uint256 lastInterest =
getStorageLastStakedInterestPrice(_property, _user);
/**
* Gets the latest cumulative sum of the interest price.
*/
(
uint256 reward,
uint256 holders,
uint256 interest,
uint256 holdersCap
) = calculateCumulativeRewardPrices();
/**
* Calculates and returns the latest withdrawable reward amount from the difference.
*/
uint256 result =
interest >= lastInterest
? interest.sub(lastInterest).mul(lockedUpPerAccount).divBasis()
: 0;
return (
result,
interest,
RewardPrices(reward, holders, interest, holdersCap)
);
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/
function _calculateWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256 _amount, RewardPrices memory _prices) {
/**
* If the passed Property has not authenticated, returns always 0.
*/
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return (0, RewardPrices(0, 0, 0, 0));
}
/**
* Gets the reward amount in saved without withdrawal.
*/
uint256 pending = getStoragePendingInterestWithdrawal(_property, _user);
/**
* Gets the reward amount of before DIP4.
*/
uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user);
/**
* Gets the latest withdrawal reward amount.
*/
(uint256 amount, , RewardPrices memory prices) =
_calculateInterestAmount(_property, _user);
/**
* Returns the sum of all values.
*/
uint256 withdrawableAmount = amount.add(pending).add(legacy);
return (withdrawableAmount, prices);
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from external of the contract)
*/
function calculateWithdrawableInterestAmount(
address _property,
address _user
) public view returns (uint256) {
(uint256 amount, ) =
_calculateWithdrawableInterestAmount(_property, _user);
return amount;
}
/**
* Withdraws staking reward as an interest.
*/
function _withdrawInterest(address _property)
private
returns (RewardPrices memory _prices)
{
/**
* Gets the withdrawable amount.
*/
(uint256 value, RewardPrices memory prices) =
_calculateWithdrawableInterestAmount(_property, msg.sender);
/**
* Sets the unwithdrawn reward amount to 0.
*/
setStoragePendingInterestWithdrawal(_property, msg.sender, 0);
/**
* Updates the staking status to avoid double rewards.
*/
setStorageLastStakedInterestPrice(
_property,
msg.sender,
prices.interest
);
__updateLegacyWithdrawableInterestAmount(_property, msg.sender);
/**
* Mints the reward.
*/
require(
IDevMinter(devMinter).mint(msg.sender, value),
"dev mint failed"
);
/**
* Since the total supply of tokens has changed, updates the latest maximum mint amount.
*/
update();
return prices;
}
/**
* Status updates with the addition or release of staking.
*/
function updateValues(
bool _addition,
address _account,
address _property,
uint256 _value,
RewardPrices memory _prices
) private {
beforeStakesChanged(_property, _account, _prices);
/**
* If added staking:
*/
if (_addition) {
/**
* Updates the current staking amount of the protocol total.
*/
addAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
addPropertyValue(_property, _value);
/**
* Updates the user's current staking amount in the Property.
*/
addValue(_property, _account, _value);
/**
* If released staking:
*/
} else {
/**
* Updates the current staking amount of the protocol total.
*/
subAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
subPropertyValue(_property, _value);
/**
* Updates the current staking amount of the Property.
*/
subValue(_property, _account, _value);
}
/**
* Since each staking amount has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Returns the staking amount of the protocol total.
*/
function getAllValue() external view returns (uint256) {
return getStorageAllValue();
}
/**
* Adds the staking amount of the protocol total.
*/
function addAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.add(_value);
setStorageAllValue(value);
}
/**
* Subtracts the staking amount of the protocol total.
*/
function subAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.sub(_value);
setStorageAllValue(value);
}
/**
* Returns the user's staking amount in the Property.
*/
function getValue(address _property, address _sender)
external
view
returns (uint256)
{
return getStorageValue(_property, _sender);
}
/**
* Adds the user's staking amount in the Property.
*/
function addValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.add(_value);
setStorageValue(_property, _sender, value);
}
/**
* Subtracts the user's staking amount in the Property.
*/
function subValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.sub(_value);
setStorageValue(_property, _sender, value);
}
/**
* Returns whether the user is staking in the Property.
*/
function hasValue(
address _property,
address _sender,
uint256 _amount
) private view returns (bool) {
uint256 value = getStorageValue(_property, _sender);
return value >= _amount;
}
/**
* Returns the staking amount of the Property.
*/
function getPropertyValue(address _property)
external
view
returns (uint256)
{
return getStoragePropertyValue(_property);
}
/**
* Adds the staking amount of the Property.
*/
function addPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
value = value.add(_value);
setStoragePropertyValue(_property, value);
}
/**
* Subtracts the staking amount of the Property.
*/
function subPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
uint256 nextValue = value.sub(_value);
setStoragePropertyValue(_property, nextValue);
}
/**
* Saves the latest reward amount as an undrawn amount.
*/
function updatePendingInterestWithdrawal(address _property, address _user)
private
returns (RewardPrices memory _prices)
{
/**
* Gets the latest reward amount.
*/
(uint256 withdrawableAmount, RewardPrices memory prices) =
_calculateWithdrawableInterestAmount(_property, _user);
/**
* Saves the amount to `PendingInterestWithdrawal` storage.
*/
setStoragePendingInterestWithdrawal(
_property,
_user,
withdrawableAmount
);
/**
* Updates the reward amount of before DIP4 to prevent further addition it.
*/
__updateLegacyWithdrawableInterestAmount(_property, _user);
return prices;
}
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the staking amount.
*/
function __legacyWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
uint256 _last = getStorageLastInterestPrice(_property, _user);
uint256 price = getStorageInterestPrice(_property);
uint256 priceGap = price.sub(_last);
uint256 lockedUpValue = getStorageValue(_property, _user);
uint256 value = priceGap.mul(lockedUpValue);
return value.divBasis();
}
/**
* Updates and treats the reward of before DIP4 as already received.
*/
function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
) private {
uint256 interestPrice = getStorageInterestPrice(_property);
if (getStorageLastInterestPrice(_property, _user) != interestPrice) {
setStorageLastInterestPrice(_property, _user, interestPrice);
}
}
function ___setFallbackInitialCumulativeHoldersRewardCap(uint256 _value)
external
onlyOwner
{
setStorageFallbackInitialCumulativeHoldersRewardCap(_value);
}
} | LastCumulativeHoldersRewardPricePerProperty | function setStorageLastCumulativeHoldersRewardPricePerProperty(
address _property,
uint256 _price
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property),
_price
);
}
| 2,011,242 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface IERC677Receiver {
function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface ISideToken {
function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface ISideTokenFactory {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address);
event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
// https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
// solium-disable-next-line security/no-inline-assembly
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./zeppelin/token/ERC777/ERC777.sol";
import "./IERC677Receiver.sol";
import "./ISideToken.sol";
import "./LibEIP712.sol";
contract SideToken is ISideToken, ERC777 {
using Address for address;
using SafeMath for uint256;
address public minter;
uint256 private _granularity;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
// ERC677 Transfer Event
event Transfer(address,address,uint256,bytes);
constructor(string memory _tokenName, string memory _tokenSymbol, address _minterAddr, uint256 _newGranularity)
ERC777(_tokenName, _tokenSymbol, new address[](0)) {
require(_minterAddr != address(0), "SideToken: Empty Minter");
require(_newGranularity >= 1, "SideToken: Granularity < 1");
minter = _minterAddr;
_granularity = _newGranularity;
uint chainId;
// solium-disable-next-line security/no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(
name(),
"1",
chainId,
address(this)
);
}
modifier onlyMinter() {
require(_msgSender() == minter, "SideToken: Caller is not the minter");
_;
}
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external onlyMinter override
{
_mint(_msgSender(), account, amount, userData, operatorData);
}
/**
* @dev ERC677 transfer token with additional data if the recipient is a contact.
* @param recipient The address to transfer to.
* @param amount The amount to be transferred.
* @param data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address recipient, uint amount, bytes calldata data)
external returns (bool success)
{
address from = _msgSender();
_send(from, from, recipient, amount, data, "", false);
emit Transfer(from, recipient, amount, data);
IERC677Receiver(recipient).onTokenTransfer(from, amount, data);
return true;
}
function granularity() public view override returns (uint256) {
return _granularity;
}
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "SideToken: EXPIRED");
bytes32 digest = LibEIP712.hashEIP712Message(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "SideToken: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./zeppelin/ownership/Secondary.sol";
import "./ISideTokenFactory.sol";
import "./SideToken.sol";
contract SideTokenFactory is ISideTokenFactory, Secondary {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity)
external onlyPrimary override returns(address) {
address sideToken = address(new SideToken(name, symbol, primary(), granularity));
emit SideTokenCreated(sideToken, symbol, granularity);
return sideToken;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/*
* @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 returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `_account`.
* - `_interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `_implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address _account, bytes32 _interfaceHash, address _implementer) external;
/**
* @dev Returns the implementer of `_interfaceHash` for `_account`. If no such
* implementer is registered, returns the zero address.
*
* If `_interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `_account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address _account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../GSN/Context.sol";
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
abstract contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () {
_primary = _msgSender();
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../GSN/Context.sol";
import "./IERC777.sol";
import "./IERC777Recipient.sol";
import "./IERC777Sender.sol";
import "../../token/ERC20/IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../introspection/IERC1820Registry.sol";
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory aName,
string memory aSymbol,
address[] memory theDefaultOperators
) {
_name = aName;
_symbol = aSymbol;
_defaultOperatorsArray = theDefaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override(IERC777) returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override(IERC777) returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure override returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override(IERC777) returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external override(IERC777) {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes calldata data) external override(IERC777) {
_burn(_msgSender(), _msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override(IERC777) returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external override(IERC777) {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external override(IERC777) {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override(IERC777) returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external override(IERC777)
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator");
_send(_msgSender(), sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData)
external override(IERC777) {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator");
_burn(_msgSender(), account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender)
public view override(IERC20) returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external override(IERC20) returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount)
external override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
require(holder != address(0), "ERC777: transfer from zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
require(account != address(0), "ERC777: mint to zero address");
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from zero address");
require(to != address(0), "ERC777: send to zero address");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal
{
require(from != address(0), "ERC777: burn from zero address");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
function _approve(address holder, address spender, uint256 value) internal {
// TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is
// currently unnecessary.
//require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See `IERC1820Registry` and
* `ERC1820Implementer`.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See `IERC777Sender` and `IERC777Recipient`.
*
* Emits a `Sent` event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the `tokensReceived`
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See `IERC777Sender`.
*
* Emits a `Burned` event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See `operatorSend` and `operatorBurn`.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See `isOperatorFor`.
*
* Emits an `AuthorizedOperator` event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Make an account an operator of the caller.
*
* See `isOperatorFor` and `defaultOperators`.
*
* Emits a `RevokedOperator` event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if `authorizeOperator` was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* `revokeOperator`, in which case `isOperatorFor` will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See `IERC777Sender` and `IERC777Recipient`.
*
* Emits a `Sent` event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the `tokensReceived`
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See `IERC777Sender`.
*
* Emits a `Burned` event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
function decimals() external returns (uint8);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of `IERC777` tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* See `IERC1820Registry` and `ERC1820Implementer`.
*/
interface IERC777Recipient {
/**
* @dev Called by an `IERC777` token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* `IERC777.balanceOf`, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* `IERC777` Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* See `IERC1820Registry` and `ERC1820Implementer`.
*/
interface IERC777Sender {
/**
* @dev Called by an `IERC777` token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* `IERC777.balanceOf`, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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 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: 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);
}
}
}
}
| See {IERC20-transferFrom}. Note that operator and allowance concepts are orthogonal: operators cannot call `transferFrom` (unless they have allowance), and accounts with allowance cannot call `operatorSend` (unless they are operators). Emits {Sent}, {Transfer} and {Approval} events./ | function transferFrom(address holder, address recipient, uint256 amount)
external override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
require(holder != address(0), "ERC777: transfer from zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
| 1,423,177 |
./full_match/5/0x3B95c63382b0C6b0eC49395cCe59DE5d6fd1276F/sources/project_/contracts/erc721a/contracts/ERC721A.sol | Returns the number of tokens burned by or on behalf of `owner`./ | function _numberBurned(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
| 7,080,149 |
/**
*Submitted for verification at Etherscan.io on 2021-08-17
*/
/**
* Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library MathUtil {
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return divCeil(a, b, "SafeMath: division by zero");
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
interface IPriceFeeds {
function queryRate(
address sourceToken,
address destToken)
external
view
returns (uint256 rate, uint256 precision);
function queryPrecision(
address sourceToken,
address destToken)
external
view
returns (uint256 precision);
function queryReturn(
address sourceToken,
address destToken,
uint256 sourceAmount)
external
view
returns (uint256 destAmount);
function checkPriceDisagreement(
address sourceToken,
address destToken,
uint256 sourceAmount,
uint256 destAmount,
uint256 maxSlippage)
external
view
returns (uint256 sourceToDestSwapRate);
function amountInEth(
address Token,
uint256 amount)
external
view
returns (uint256 ethAmount);
function getMaxDrawdown(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (uint256);
function getCurrentMarginAndCollateralSize(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralInEthAmount);
function getCurrentMargin(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralToLoanRate);
function shouldLiquidate(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (bool);
function getFastGasPrice(
address payToken)
external
view
returns (uint256);
}
contract IVestingToken is IERC20 {
function claim()
external;
function vestedBalanceOf(
address _owner)
external
view
returns (uint256);
function claimedBalanceOf(
address _owner)
external
view
returns (uint256);
}
/**
* @dev Library for managing loan sets
*
* 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.
*
* Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`.
*
*/
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
/**
* @dev Add an address value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return addBytes32(set, value);
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes an address value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return removeBytes32(set, value);
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function containsAddress(Bytes32Set storage set, address addrvalue)
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* 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.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(Bytes32Set storage set, uint256 start, uint256 count)
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(Bytes32Set storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function get(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return set.values[index];
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function getAddress(Bytes32Set storage set, uint256 index)
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
interface IUniswapV2Router {
// 0x38ed1739
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x8803dbee
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x1f00ca74
function getAmountsIn(
uint256 amountOut,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
// 0xd06ca61f
function getAmountsOut(
uint256 amountIn,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface ICurve3Pool {
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount)
external;
function get_virtual_price()
external
view
returns (uint256);
}
/// @title A proxy interface for The Protocol
/// @author bZeroX
/// @notice This is just an interface, not to be deployed itself.
/// @dev This interface is to be used for the protocol interactions.
interface IBZx {
////// Protocol //////
/// @dev adds or replaces existing proxy module
/// @param target target proxy module address
function replaceContract(address target) external;
/// @dev updates all proxy modules addreses and function signatures.
/// sigsArr and targetsArr should be of equal length
/// @param sigsArr array of function signatures
/// @param targetsArr array of target proxy module addresses
function setTargets(
string[] calldata sigsArr,
address[] calldata targetsArr
) external;
/// @dev returns protocol module address given a function signature
/// @return module address
function getTarget(string calldata sig) external view returns (address);
////// Protocol Settings //////
/// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface
/// @param newContract module address for the IPriceFeeds implementation
function setPriceFeedContract(address newContract) external;
/// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface
/// @param newContract module address for the ISwapsImpl implementation
function setSwapsImplContract(address newContract) external;
/// @dev sets loan pool with assets. Accepts two arrays of equal length
/// @param pools array of address of pools
/// @param assets array of addresses of assets
function setLoanPool(address[] calldata pools, address[] calldata assets)
external;
/// @dev updates list of supported tokens, it can be use also to disable or enable particualr token
/// @param addrs array of address of pools
/// @param toggles array of addresses of assets
/// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.)
function setSupportedTokens(
address[] calldata addrs,
bool[] calldata toggles,
bool withApprovals
) external;
/// @dev sets lending fee with WEI_PERCENT_PRECISION
/// @param newValue lending fee percent
function setLendingFeePercent(uint256 newValue) external;
/// @dev sets trading fee with WEI_PERCENT_PRECISION
/// @param newValue trading fee percent
function setTradingFeePercent(uint256 newValue) external;
/// @dev sets borrowing fee with WEI_PERCENT_PRECISION
/// @param newValue borrowing fee percent
function setBorrowingFeePercent(uint256 newValue) external;
/// @dev sets affiliate fee with WEI_PERCENT_PRECISION
/// @param newValue affiliate fee percent
function setAffiliateFeePercent(uint256 newValue) external;
/// @dev sets liquidation inncetive percent per loan per token. This is the profit percent
/// that liquidator gets in the process of liquidating.
/// @param loanTokens array list of loan tokens
/// @param collateralTokens array list of collateral tokens
/// @param amounts array list of liquidation inncetive amount
function setLiquidationIncentivePercent(
address[] calldata loanTokens,
address[] calldata collateralTokens,
uint256[] calldata amounts
) external;
/// @dev sets max swap rate slippage percent.
/// @param newAmount max swap rate slippage percent.
function setMaxDisagreement(uint256 newAmount) external;
/// TODO
function setSourceBufferPercent(uint256 newAmount) external;
/// @dev sets maximum supported swap size in ETH
/// @param newAmount max swap size in ETH.
function setMaxSwapSize(uint256 newAmount) external;
/// @dev sets fee controller address
/// @param newController address of the new fees controller
function setFeesController(address newController) external;
/// @dev withdraws lending fees to receiver. Only can be called by feesController address
/// @param tokens array of token addresses.
/// @param receiver fees receiver address
/// @return amounts array of amounts withdrawn
function withdrawFees(
address[] calldata tokens,
address receiver,
FeeClaimType feeType
) external returns (uint256[] memory amounts);
/// @dev withdraw protocol token (BZRX) from vesting contract vBZRX
/// @param receiver address of BZRX tokens claimed
/// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance.
/// @return rewardToken reward token address
/// @return withdrawAmount amount
function withdrawProtocolToken(address receiver, uint256 amount)
external
returns (address rewardToken, uint256 withdrawAmount);
/// @dev depozit protocol token (BZRX)
/// @param amount address of BZRX tokens to deposit
function depositProtocolToken(uint256 amount) external;
function grantRewards(address[] calldata users, uint256[] calldata amounts)
external
returns (uint256 totalAmount);
// NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input
function queryFees(address[] calldata tokens, FeeClaimType feeType)
external
view
returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);
function priceFeeds() external view returns (address);
function swapsImpl() external view returns (address);
function logicTargets(bytes4) external view returns (address);
function loans(bytes32) external view returns (Loan memory);
function loanParams(bytes32) external view returns (LoanParams memory);
// we don't use this yet
// function lenderOrders(address, bytes32) external returns (Order memory);
// function borrowerOrders(address, bytes32) external returns (Order memory);
function delegatedManagers(bytes32, address) external view returns (bool);
function lenderInterest(address, address)
external
view
returns (LenderInterest memory);
function loanInterest(bytes32) external view returns (LoanInterest memory);
function feesController() external view returns (address);
function lendingFeePercent() external view returns (uint256);
function lendingFeeTokensHeld(address) external view returns (uint256);
function lendingFeeTokensPaid(address) external view returns (uint256);
function borrowingFeePercent() external view returns (uint256);
function borrowingFeeTokensHeld(address) external view returns (uint256);
function borrowingFeeTokensPaid(address) external view returns (uint256);
function protocolTokenHeld() external view returns (uint256);
function protocolTokenPaid() external view returns (uint256);
function affiliateFeePercent() external view returns (uint256);
function liquidationIncentivePercent(address, address)
external
view
returns (uint256);
function loanPoolToUnderlying(address) external view returns (address);
function underlyingToLoanPool(address) external view returns (address);
function supportedTokens(address) external view returns (bool);
function maxDisagreement() external view returns (uint256);
function sourceBufferPercent() external view returns (uint256);
function maxSwapSize() external view returns (uint256);
/// @dev get list of loan pools in the system. Ordering is not guaranteed
/// @param start start index
/// @param count number of pools to return
/// @return loanPoolsList array of loan pools
function getLoanPoolsList(uint256 start, uint256 count)
external
view
returns (address[] memory loanPoolsList);
/// @dev checks whether addreess is a loan pool address
/// @return boolean
function isLoanPool(address loanPool) external view returns (bool);
////// Loan Settings //////
/// @dev creates new loan param settings
/// @param loanParamsList array of LoanParams
/// @return loanParamsIdList array of loan ids created
function setupLoanParams(LoanParams[] calldata loanParamsList)
external
returns (bytes32[] memory loanParamsIdList);
/// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected.
/// @param loanParamsIdList array of loan ids
function disableLoanParams(bytes32[] calldata loanParamsIdList) external;
/// @dev gets array of LoanParams by given ids
/// @param loanParamsIdList array of loan ids
/// @return loanParamsList array of LoanParams
function getLoanParams(bytes32[] calldata loanParamsIdList)
external
view
returns (LoanParams[] memory loanParamsList);
/// @dev Enumerates LoanParams in the system by owner
/// @param owner of the loan params
/// @param start number of loans to return
/// @param count total number of the items
/// @return loanParamsList array of LoanParams
function getLoanParamsList(
address owner,
uint256 start,
uint256 count
) external view returns (bytes32[] memory loanParamsList);
/// @dev returns total loan principal for token address
/// @param lender address
/// @param loanToken address
/// @return total principal of the loan
function getTotalPrincipal(address lender, address loanToken)
external
view
returns (uint256);
////// Loan Openings //////
/// @dev This is THE function that borrows or trades on the protocol
/// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function
/// @param loanId id of existing loan, if 0, start a new loan
/// @param isTorqueLoan boolean whether it is toreque or non torque loan
/// @param initialMargin in WEI_PERCENT_PRECISION
/// @param sentAddresses array of size 4:
/// lender: must match loan if loanId provided
/// borrower: must match loan if loanId provided
/// receiver: receiver of funds (address(0) assumes borrower address)
/// manager: delegated manager of loan unless address(0)
/// @param sentValues array of size 5:
/// newRate: new loan interest rate
/// newPrincipal: new loan size (borrowAmount + any borrowed interest)
/// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length)
/// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans)
/// collateralTokenReceived: total collateralToken deposit
/// @param loanDataBytes required when sending ether
/// @return principal of the loan and collateral amount
function borrowOrTradeFromPool(
bytes32 loanParamsId,
bytes32 loanId,
bool isTorqueLoan,
uint256 initialMargin,
address[4] calldata sentAddresses,
uint256[5] calldata sentValues,
bytes calldata loanDataBytes
) external payable returns (LoanOpenData memory);
/// @dev sets/disables/enables the delegated manager for the loan
/// @param loanId id of the loan
/// @param delegated delegated manager address
/// @param toggle boolean set enabled or disabled
function setDelegatedManager(
bytes32 loanId,
address delegated,
bool toggle
) external;
/// @dev estimates margin exposure for simulated position
/// @param loanToken address of the loan token
/// @param collateralToken address of collateral token
/// @param loanTokenSent amout of loan token sent
/// @param collateralTokenSent amount of collateral token sent
/// @param interestRate yearly interest rate
/// @param newPrincipal principal amount of the loan
/// @return estimated margin exposure amount
function getEstimatedMarginExposure(
address loanToken,
address collateralToken,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 interestRate,
uint256 newPrincipal
) external view returns (uint256);
/// @dev calculates required collateral for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param newPrincipal principal amount of the loan
/// @param marginAmount margin amount of the loan
/// @param isTorqueLoan boolean torque or non torque loan
/// @return collateralAmountRequired amount required
function getRequiredCollateral(
address loanToken,
address collateralToken,
uint256 newPrincipal,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 collateralAmountRequired);
function getRequiredCollateralByParams(
bytes32 loanParamsId,
uint256 newPrincipal
) external view returns (uint256 collateralAmountRequired);
/// @dev calculates borrow amount for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param collateralTokenAmount amount of collateral token sent
/// @param marginAmount margin amount
/// @param isTorqueLoan boolean torque or non torque loan
/// @return borrowAmount possible borrow amount
function getBorrowAmount(
address loanToken,
address collateralToken,
uint256 collateralTokenAmount,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 borrowAmount);
function getBorrowAmountByParams(
bytes32 loanParamsId,
uint256 collateralTokenAmount
) external view returns (uint256 borrowAmount);
////// Loan Closings //////
/// @dev liquidates unhealty loans
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount amount of the collateral token of the loan
/// @return seizedAmount sezied amount in the collateral token
/// @return seizedToken loan token address
function liquidate(
bytes32 loanId,
address receiver,
uint256 closeAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param loanDataBytes reserved for future use.
function rollover(bytes32 loanId, bytes calldata loanDataBytes)
external
returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param depositAmount amount of loan token to deposit
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDeposit(
bytes32 loanId,
address receiver,
uint256 depositAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param swapAmount amount of loan token to swap
/// @param returnTokenIsCollateral boolean whether to return tokens is collateral
/// @param loanDataBytes reserved for future use
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount, // denominated in collateralToken
bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Closings With Gas Token //////
/// @dev liquidates unhealty loans by using Gas token
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param gasTokenUser user address of the GAS token
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return seizedAmount loan token withdraw amount
/// @return seizedToken loan token address
function liquidateWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 closeAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param gasTokenUser user address of the GAS token
function rolloverWithGasToken(
bytes32 loanId,
address gasTokenUser,
bytes calldata /*loanDataBytes*/
) external returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param depositAmount amount of loan token to deposit denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDepositWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 depositAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param swapAmount amount of loan token to swap denominated in collateralToken
/// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwapWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Maintenance //////
/// @dev deposit collateral to existing loan
/// @param loanId existing loan id
/// @param depositAmount amount to deposit which must match msg.value if ether is sent
function depositCollateral(bytes32 loanId, uint256 depositAmount)
external
payable;
/// @dev withdraw collateral from existing loan
/// @param loanId existing lona id
/// @param receiver address of withdrawn tokens
/// @param withdrawAmount amount to withdraw
/// @return actualWithdrawAmount actual amount withdrawn
function withdrawCollateral(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 actualWithdrawAmount);
/// @dev withdraw accrued interest rate for a loan given token address
/// @param loanToken loan token address
function withdrawAccruedInterest(address loanToken) external;
/// @dev extends loan duration by depositing more collateral
/// @param loanId id of the existing loan
/// @param depositAmount amount to deposit
/// @param useCollateral boolean whether to extend using collateral or deposit amount
/// @return secondsExtended by that number of seconds loan duration was extended
function extendLoanDuration(
bytes32 loanId,
uint256 depositAmount,
bool useCollateral,
bytes calldata // for future use /*loanDataBytes*/
) external payable returns (uint256 secondsExtended);
/// @dev reduces loan duration by withdrawing collateral
/// @param loanId id of the existing loan
/// @param receiver address to receive tokens
/// @param withdrawAmount amount to withdraw
/// @return secondsReduced by that number of seconds loan duration was extended
function reduceLoanDuration(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 secondsReduced);
function setDepositAmount(
bytes32 loanId,
uint256 depositValueAsLoanToken,
uint256 depositValueAsCollateralToken
) external;
function claimRewards(address receiver)
external
returns (uint256 claimAmount);
function transferLoan(bytes32 loanId, address newOwner) external;
function rewardsBalanceOf(address user)
external
view
returns (uint256 rewardsBalance);
/// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token
/// @param lender The lender address
/// @param loanToken The loan token address
/// @return interestPaid The total amount of interest that has been paid to a lender so far
/// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet
/// @return interestOwedPerDay The amount of interest the lender is earning per day
/// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn
/// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender
/// @return principalTotal The total amount of outstading principal the lender has loaned
function getLenderInterestData(address lender, address loanToken)
external
view
returns (
uint256 interestPaid,
uint256 interestPaidDate,
uint256 interestOwedPerDay,
uint256 interestUnPaid,
uint256 interestFeePercent,
uint256 principalTotal
);
/// @dev Gets current interest data for a loan
/// @param loanId A unique id representing the loan
/// @return loanToken The loan token that interest is paid in
/// @return interestOwedPerDay The amount of interest the borrower is paying per day
/// @return interestDepositTotal The total amount of interest the borrower has deposited
/// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender
function getLoanInterestData(bytes32 loanId)
external
view
returns (
address loanToken,
uint256 interestOwedPerDay,
uint256 interestDepositTotal,
uint256 interestDepositRemaining
);
/// @dev gets list of loans of particular user address
/// @param user address of the loans
/// @param start of the index
/// @param count number of loans to return
/// @param loanType type of the loan: All(0), Margin(1), NonMargin(2)
/// @param isLender whether to list lender loans or borrower loans
/// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation
/// @return loansData LoanReturnData array of loans
function getUserLoans(
address user,
uint256 start,
uint256 count,
LoanType loanType,
bool isLender,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
function getUserLoansCount(address user, bool isLender)
external
view
returns (uint256);
/// @dev gets existing loan
/// @param loanId id of existing loan
/// @return loanData array of loans
function getLoan(bytes32 loanId)
external
view
returns (LoanReturnData memory loanData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
function getActiveLoans(
uint256 start,
uint256 count,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
/// @param isLiquidatable boolean if true return liquidatable loans only
function getActiveLoansAdvanced(
uint256 start,
uint256 count,
bool unsafeOnly,
bool isLiquidatable
) external view returns (LoanReturnData[] memory loansData);
function getActiveLoansCount() external view returns (uint256);
////// Swap External //////
/// @dev swap thru external integration
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternal(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev swap thru external integration using GAS
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param gasTokenUser user address of the GAS token
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternalWithGasToken(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
address gasTokenUser,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev calculate simulated return of swap
/// @param sourceToken source token address
/// @param destToken destination token address
/// @param sourceTokenAmount source token amount
/// @return amoun denominated in destination token
function getSwapExpectedReturn(
address sourceToken,
address destToken,
uint256 sourceTokenAmount
) external view returns (uint256);
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
struct LoanParams {
bytes32 id;
bool active;
address owner;
address loanToken;
address collateralToken;
uint256 minInitialMargin;
uint256 maintenanceMargin;
uint256 maxLoanTerm;
}
struct LoanOpenData {
bytes32 loanId;
uint256 principal;
uint256 collateral;
}
enum LoanType {
All,
Margin,
NonMargin
}
struct LoanReturnData {
bytes32 loanId;
uint96 endTimestamp;
address loanToken;
address collateralToken;
uint256 principal;
uint256 collateral;
uint256 interestOwedPerDay;
uint256 interestDepositRemaining;
uint256 startRate;
uint256 startMargin;
uint256 maintenanceMargin;
uint256 currentMargin;
uint256 maxLoanTerm;
uint256 maxLiquidatable;
uint256 maxSeizable;
uint256 depositValueAsLoanToken;
uint256 depositValueAsCollateralToken;
}
enum FeeClaimType {
All,
Lending,
Trading,
Borrowing
}
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset
uint256 owedPerDay; // interest owed per day for all loans of asset
uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term)
uint256 paidTotal; // total interest paid so far for asset
uint256 updatedTimestamp; // last update
}
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan
uint256 depositTotal; // total escrowed interest for loan
uint256 updatedTimestamp; // last update
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IMasterChefSushi {
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
function deposit(uint256 _pid, uint256 _amount)
external;
function withdraw(uint256 _pid, uint256 _amount)
external;
// Info of each user that stakes LP tokens.
function userInfo(uint256, address)
external
view
returns (UserInfo memory);
function pendingSushi(uint256 _pid, address _user)
external
view
returns (uint256);
}
interface IStaking {
struct AltRewardsUserInfo {
uint256 rewardsPerShare;
uint256 pendingRewards;
}
function pendingSushiRewards(address _user)
external
view
returns (uint256);
function getCurrentFeeTokens()
external
view
returns (address[] memory);
function maxUniswapDisagreement()
external
view
returns (uint256);
//Temporary, will remove it after migrationn
function stakingRewards(address)
external
view
returns (uint256);
function isPaused()
external
view
returns (bool);
function fundsWallet()
external
view
returns (address);
function callerRewardDivisor()
external
view
returns (uint256);
function maxCurveDisagreement()
external
view
returns (uint256);
function rewardPercent()
external
view
returns (uint256);
function addRewards(uint256 newBZRX, uint256 newStableCoin)
external;
function stake(
address[] calldata tokens,
uint256[] calldata values
)
external;
function stake(
address[] calldata tokens,
uint256[] calldata values,
bool claimSushi
)
external;
function unstake(
address[] calldata tokens,
uint256[] calldata values
)
external;
function unstake(
address[] calldata tokens,
uint256[] calldata values,
bool claimSushi
)
external;
function earned(address account)
external
view
returns (
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting
);
function getVariableWeights()
external
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight);
function balanceOfByAsset(
address token,
address account)
external
view
returns (uint256 balance);
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
);
function balanceOfStored(
address account)
external
view
returns (uint256 vestedBalance, uint256 vestingBalance);
function totalSupplyStored()
external
view
returns (uint256 supply);
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
external
view
returns (uint256 vested);
function votingBalanceOf(
address account,
uint256 proposalId)
external
view
returns (uint256 totalVotes);
function votingBalanceOfNow(
address account)
external
view
returns (uint256 totalVotes);
function _setProposalVals(
address account,
uint256 proposalId)
external
returns (uint256);
function exit()
external;
function addAltRewards(address token, uint256 amount)
external;
function pendingAltRewards(address token, address _user)
external
view
returns (uint256);
}
contract StakingConstants {
address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3;
address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F;
address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157;
address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap
address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer
IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2;
IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap
ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5
uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4
uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5
uint256 internal constant vestingStartTimestamp = 1594648800; // start_time
uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration;
uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration;
uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX
address internal constant SUSHI_MASTERCHEF = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd;
uint256 internal constant BZRX_ETH_SUSHI_MASTERCHEF_PID = 188;
uint256 public constant BZRXWeightStored = 1e18;
struct DelegatedTokens {
address user;
uint256 BZRX;
uint256 vBZRX;
uint256 iBZRX;
uint256 LPToken;
uint256 totalVotes;
}
event Stake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event Unstake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event AddRewards(
address indexed sender,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event Claim(
address indexed user,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event ChangeDelegate(
address indexed user,
address indexed oldDelegate,
address indexed newDelegate
);
event WithdrawFees(
address indexed sender
);
event ConvertFees(
address indexed sender,
uint256 bzrxOutput,
uint256 stableCoinOutput
);
event DistributeFees(
address indexed sender,
uint256 bzrxRewards,
uint256 stableCoinRewards
);
event AddAltRewards(
address indexed sender,
address indexed token,
uint256 amount
);
event ClaimAltRewards(
address indexed user,
address indexed token,
uint256 amount
);
}
contract StakingUpgradeable is Ownable {
address public implementation;
}
contract StakingState is StakingUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18;
address internal constant ZERO_ADDRESS = address(0);
bool public isPaused;
address public fundsWallet;
mapping(address => uint256) internal _totalSupplyPerToken; // token => value
mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value
mapping(address => address) public delegate; // user => delegate
mapping(address => mapping(address => uint256)) public delegatedPerToken; // token => user => value
uint256 public bzrxPerTokenStored;
mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value
mapping(address => uint256) public bzrxRewards; // user => value
mapping(address => uint256) public bzrxVesting; // user => value
uint256 public stableCoinPerTokenStored;
mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value
mapping(address => uint256) public stableCoinRewards; // user => value
mapping(address => uint256) public stableCoinVesting; // user => value
uint256 public vBZRXWeightStored;
uint256 public iBZRXWeightStored;
uint256 public LPTokenWeightStored;
EnumerableBytes32Set.Bytes32Set internal _delegatedSet;
uint256 public lastRewardsAddTime;
mapping(address => uint256) public vestingLastSync;
mapping(address => address[]) public swapPaths;
mapping(address => uint256) public stakingRewards;
uint256 public rewardPercent = 50e18;
uint256 public maxUniswapDisagreement = 3e18;
uint256 public maxCurveDisagreement = 3e18;
uint256 public callerRewardDivisor = 100;
address[] public currentFeeTokens;
struct ProposalState {
uint256 proposalTime;
uint256 iBZRXWeight;
uint256 lpBZRXBalance;
uint256 lpTotalSupply;
}
address public governor;
mapping(uint256 => ProposalState) internal _proposalState;
mapping(address => uint256[]) public altRewardsRounds; // depreciated
mapping(address => uint256) public altRewardsPerShare; // token => value
// Token => (User => Info)
mapping(address => mapping(address => IStaking.AltRewardsUserInfo)) public userAltRewardsPerShare;
}
contract StakingV1_1 is StakingState, StakingConstants {
using MathUtil for uint256;
modifier onlyEOA() {
require(msg.sender == tx.origin, "unauthorized");
_;
}
modifier checkPause() {
require(!isPaused, "paused");
_;
}
function getCurrentFeeTokens()
external
view
returns (address[] memory)
{
return currentFeeTokens;
}
// View function to see pending sushi rewards on frontend.
function pendingSushiRewards(address _user)
public
view
returns (uint256)
{
uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF)
.pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this));
return _pendingAltRewards(
SUSHI,
_user,
balanceOfByAsset(LPToken, _user),
pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken])
);
}
function pendingAltRewards(address token, address _user)
external
view
returns (uint256)
{
uint256 userSupply = balanceOfByAsset(token, _user);
return _pendingAltRewards(token, _user, userSupply, 0);
}
function _pendingAltRewards(address token, address _user, uint256 userSupply, uint256 extraRewardsPerShare)
internal
view
returns (uint256)
{
uint256 _altRewardsPerShare = altRewardsPerShare[token].add(extraRewardsPerShare);
if (_altRewardsPerShare == 0)
return 0;
if (userSupply == 0)
return 0;
IStaking.AltRewardsUserInfo memory altRewardsUserInfo = userAltRewardsPerShare[_user][token];
return altRewardsUserInfo.pendingRewards.add(
(_altRewardsPerShare.sub(altRewardsUserInfo.rewardsPerShare)).mul(userSupply).div(1e12)
);
}
// Withdraw all from sushi masterchef
function exitSushi()
external
onlyOwner
{
IMasterChefSushi chef = IMasterChefSushi(SUSHI_MASTERCHEF);
uint256 balance = chef.userInfo(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)).amount;
chef.withdraw(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
balance
);
}
function _depositToSushiMasterchef(uint256 amount)
internal
{
uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this));
IMasterChefSushi(SUSHI_MASTERCHEF).deposit(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
amount
);
uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore;
if (sushiRewards != 0) {
_addAltRewards(SUSHI, sushiRewards);
}
}
function _withdrawFromSushiMasterchef(uint256 amount)
internal
{
uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this));
IMasterChefSushi(SUSHI_MASTERCHEF).withdraw(
BZRX_ETH_SUSHI_MASTERCHEF_PID,
amount
);
uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore;
if (sushiRewards != 0) {
_addAltRewards(SUSHI, sushiRewards);
}
}
function stake(
address[] memory tokens,
uint256[] memory values
)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 stakeAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token");
stakeAmount = values[i];
if (stakeAmount == 0) {
continue;
}
uint256 pendingBefore = (token == LPToken) ? pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount);
_totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount);
IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount);
// Deposit to sushi masterchef
if (token == LPToken) {
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
emit Stake(
msg.sender,
token,
msg.sender, //currentDelegate,
stakeAmount
);
}
}
function unstake(
address[] memory tokens,
uint256[] memory values
)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 unstakeAmount;
uint256 stakedAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token");
unstakeAmount = values[i];
stakedAmount = _balancesPerToken[token][msg.sender];
if (unstakeAmount == 0 || stakedAmount == 0) {
continue;
}
if (unstakeAmount > stakedAmount) {
unstakeAmount = stakedAmount;
}
uint256 pendingBefore = (token == LPToken) ? pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow
_totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow
if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
// Withdraw to sushi masterchef
if (token == LPToken) {
_withdrawFromSushiMasterchef(unstakeAmount);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
IERC20(token).safeTransfer(msg.sender, unstakeAmount);
emit Unstake(
msg.sender,
token,
msg.sender, //currentDelegate,
unstakeAmount
);
}
}
function claim(
bool restake)
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 sushiRewardsEarned)
{
return _claim(restake);
}
function claimBzrx()
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(false);
emit Claim(
msg.sender,
bzrxRewardsEarned,
0
);
}
function claim3Crv()
external
checkPause
updateRewards(msg.sender)
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
0,
stableCoinRewardsEarned
);
}
function claimSushi()
external
checkPause
returns (uint256 sushiRewardsEarned)
{
sushiRewardsEarned = _claimSushi();
if(sushiRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned);
}
}
function _claim(
bool restake)
internal
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 sushiRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(restake);
stableCoinRewardsEarned = _claim3Crv();
sushiRewardsEarned = _claimSushi();
emit Claim(
msg.sender,
bzrxRewardsEarned,
stableCoinRewardsEarned
);
if(sushiRewardsEarned != 0){
emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned);
}
}
function _claimBzrx(
bool restake)
internal
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = bzrxRewards[msg.sender];
if (bzrxRewardsEarned != 0) {
bzrxRewards[msg.sender] = 0;
if (restake) {
_restakeBZRX(
msg.sender,
bzrxRewardsEarned
);
} else {
if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned);
}
}
}
function _claim3Crv()
internal
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = stableCoinRewards[msg.sender];
if (stableCoinRewardsEarned != 0) {
stableCoinRewards[msg.sender] = 0;
curve3Crv.transfer(msg.sender, stableCoinRewardsEarned);
}
}
function _claimSushi()
internal
returns (uint256)
{
address _user = msg.sender;
uint256 lptUserSupply = balanceOfByAsset(LPToken, _user);
if(lptUserSupply == 0){
return 0;
}
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
uint256 pendingSushi = _pendingAltRewards(SUSHI, _user, lptUserSupply, 0);
userAltRewardsPerShare[_user][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: 0
}
);
if (pendingSushi != 0) {
IERC20(SUSHI).safeTransfer(_user, pendingSushi);
}
return pendingSushi;
}
function _restakeBZRX(
address account,
uint256 amount)
internal
{
_balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account]
.add(amount);
_totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX]
.add(amount);
emit Stake(
account,
BZRX,
account, //currentDelegate,
amount
);
}
function exit()
public
// unstake() does a checkPause
{
address[] memory tokens = new address[](4);
uint256[] memory values = new uint256[](4);
tokens[0] = iBZRX;
tokens[1] = LPToken;
tokens[2] = vBZRX;
tokens[3] = BZRX;
values[0] = uint256(-1);
values[1] = uint256(-1);
values[2] = uint256(-1);
values[3] = uint256(-1);
unstake(tokens, values); // calls updateRewards
_claim(false);
}
modifier updateRewards(address account) {
uint256 _bzrxPerTokenStored = bzrxPerTokenStored;
uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored;
(uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned(
account,
_bzrxPerTokenStored,
_stableCoinPerTokenStored
);
bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored;
stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored;
// vesting amounts get updated before sync
bzrxVesting[account] = bzrxRewardsVesting;
stableCoinVesting[account] = stableCoinRewardsVesting;
(bzrxRewards[account], stableCoinRewards[account]) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
vestingLastSync[account] = block.timestamp;
_;
}
function earned(
address account)
external
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned)
{
(bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned(
account,
bzrxPerTokenStored,
stableCoinPerTokenStored
);
(bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
// discount vesting amounts for vesting time
uint256 multiplier = vestedBalanceForAmount(
1e36,
0,
block.timestamp
);
bzrxRewardsVesting = bzrxRewardsVesting
.sub(bzrxRewardsVesting
.mul(multiplier)
.div(1e36)
);
stableCoinRewardsVesting = stableCoinRewardsVesting
.sub(stableCoinRewardsVesting
.mul(multiplier)
.div(1e36)
);
uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF)
.pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this));
sushiRewardsEarned = _pendingAltRewards(
SUSHI,
account,
balanceOfByAsset(LPToken, account),
pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken])
);
}
function _earned(
address account,
uint256 _bzrxPerToken,
uint256 _stableCoinPerToken)
internal
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]);
uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]);
bzrxRewardsEarned = bzrxRewards[account];
stableCoinRewardsEarned = stableCoinRewards[account];
bzrxRewardsVesting = bzrxVesting[account];
stableCoinRewardsVesting = stableCoinVesting[account];
if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) {
uint256 value;
uint256 multiplier;
uint256 lastSync;
(uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account);
value = vestedBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsEarned = value
.add(bzrxRewardsEarned);
value = vestedBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsEarned = value
.add(stableCoinRewardsEarned);
if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) {
// add new vesting amount for BZRX
value = vestingBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsVesting = bzrxRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
.add(value);
}
if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) {
// add new vesting amount for 3crv
value = vestingBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsVesting = stableCoinRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
if (lastSync == 0) {
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
}
value = value
.mul(multiplier);
value /= 1e36;
stableCoinRewardsEarned = stableCoinRewardsEarned
.add(value);
}
}
}
function _syncVesting(
address account,
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting)
internal
view
returns (uint256, uint256)
{
uint256 lastVestingSync = vestingLastSync[account];
if (lastVestingSync != block.timestamp) {
uint256 rewardsVested;
uint256 multiplier = vestedBalanceForAmount(
1e36,
lastVestingSync,
block.timestamp
);
if (bzrxRewardsVesting != 0) {
rewardsVested = bzrxRewardsVesting
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
if (stableCoinRewardsVesting != 0) {
rewardsVested = stableCoinRewardsVesting
.mul(multiplier)
.div(1e36);
stableCoinRewardsEarned += rewardsVested;
}
uint256 vBZRXBalance = _balancesPerToken[vBZRX][account];
if (vBZRXBalance != 0) {
// add vested BZRX to rewards balance
rewardsVested = vBZRXBalance
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
}
return (bzrxRewardsEarned, stableCoinRewardsEarned);
}
// note: anyone can contribute rewards to the contract
function addDirectRewards(
address[] calldata accounts,
uint256[] calldata bzrxAmounts,
uint256[] calldata stableCoinAmounts)
external
checkPause
returns (uint256 bzrxTotal, uint256 stableCoinTotal)
{
require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch");
for (uint256 i = 0; i < accounts.length; i++) {
bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]);
bzrxTotal = bzrxTotal.add(bzrxAmounts[i]);
stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]);
stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]);
}
if (bzrxTotal != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal);
}
if (stableCoinTotal != 0) {
curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal);
}
}
// note: anyone can contribute rewards to the contract
function addRewards(
uint256 newBZRX,
uint256 newStableCoin)
external
checkPause
{
if (newBZRX != 0 || newStableCoin != 0) {
_addRewards(newBZRX, newStableCoin);
if (newBZRX != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX);
}
if (newStableCoin != 0) {
curve3Crv.transferFrom(msg.sender, address(this), newStableCoin);
}
}
}
function _addRewards(
uint256 newBZRX,
uint256 newStableCoin)
internal
{
(vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights();
uint256 totalTokens = totalSupplyStored();
require(totalTokens != 0, "nothing staked");
bzrxPerTokenStored = newBZRX
.mul(1e36)
.div(totalTokens)
.add(bzrxPerTokenStored);
stableCoinPerTokenStored = newStableCoin
.mul(1e36)
.div(totalTokens)
.add(stableCoinPerTokenStored);
lastRewardsAddTime = block.timestamp;
emit AddRewards(
msg.sender,
newBZRX,
newStableCoin
);
}
function addAltRewards(address token, uint256 amount) public {
if (amount != 0) {
_addAltRewards(token, amount);
IERC20(token).transferFrom(msg.sender, address(this), amount);
}
}
function _addAltRewards(address token, uint256 amount) internal {
address poolAddress = token == SUSHI ? LPToken : token;
uint256 totalSupply = _totalSupplyPerToken[poolAddress];
require(totalSupply != 0, "no deposits");
altRewardsPerShare[token] = altRewardsPerShare[token]
.add(amount.mul(1e12).div(totalSupply));
emit AddAltRewards(msg.sender, token, amount);
}
function getVariableWeights()
public
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight)
{
uint256 totalVested = vestedBalanceForAmount(
_startingVBZRXBalance,
0,
block.timestamp
);
vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible
.div(_startingVBZRXBalance);
iBZRXWeight = _calcIBZRXWeight();
uint256 lpTokenSupply = _totalSupplyPerToken[LPToken];
if (lpTokenSupply != 0) {
// staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX)
uint256 normalizedLPTokenSupply = initialCirculatingSupply +
totalVested -
_totalSupplyPerToken[BZRX];
LPTokenWeight = normalizedLPTokenSupply
.mul(1e18)
.div(lpTokenSupply);
}
}
function _calcIBZRXWeight()
internal
view
returns (uint256)
{
return IERC20(BZRX).balanceOf(iBZRX)
.mul(1e50)
.div(IERC20(iBZRX).totalSupply());
}
function balanceOfByAsset(
address token,
address account)
public
view
returns (uint256 balance)
{
balance = _balancesPerToken[token][account];
}
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
)
{
return (
balanceOfByAsset(BZRX, account),
balanceOfByAsset(iBZRX, account),
balanceOfByAsset(vBZRX, account),
balanceOfByAsset(LPToken, account),
balanceOfByAsset(LPTokenOld, account)
);
}
function balanceOfStored(
address account)
public
view
returns (uint256 vestedBalance, uint256 vestingBalance)
{
uint256 balance = _balancesPerToken[vBZRX][account];
if (balance != 0) {
vestingBalance = _balancesPerToken[vBZRX][account]
.mul(vBZRXWeightStored)
.div(1e18);
}
vestedBalance = _balancesPerToken[BZRX][account];
balance = _balancesPerToken[iBZRX][account];
if (balance != 0) {
vestedBalance = balance
.mul(iBZRXWeightStored)
.div(1e50)
.add(vestedBalance);
}
balance = _balancesPerToken[LPToken][account];
if (balance != 0) {
vestedBalance = balance
.mul(LPTokenWeightStored)
.div(1e18)
.add(vestedBalance);
}
}
function totalSupplyByAsset(
address token)
external
view
returns (uint256)
{
return _totalSupplyPerToken[token];
}
function totalSupplyStored()
public
view
returns (uint256 supply)
{
supply = _totalSupplyPerToken[vBZRX]
.mul(vBZRXWeightStored)
.div(1e18);
supply = _totalSupplyPerToken[BZRX]
.add(supply);
supply = _totalSupplyPerToken[iBZRX]
.mul(iBZRXWeightStored)
.div(1e50)
.add(supply);
supply = _totalSupplyPerToken[LPToken]
.mul(LPTokenWeightStored)
.div(1e18)
.add(supply);
}
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
public
view
returns (uint256 vested)
{
vestingEndTime = vestingEndTime.min256(block.timestamp);
if (vestingEndTime > lastUpdate) {
if (vestingEndTime <= vestingCliffTimestamp ||
lastUpdate >= vestingEndTimestamp) {
// time cannot be before vesting starts
// OR all vested token has already been claimed
return 0;
}
if (lastUpdate < vestingCliffTimestamp) {
// vesting starts at the cliff timestamp
lastUpdate = vestingCliffTimestamp;
}
if (vestingEndTime > vestingEndTimestamp) {
// vesting ends at the end timestamp
vestingEndTime = vestingEndTimestamp;
}
uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate);
vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0
}
}
// Governance Logic //
function votingBalanceOf(
address account,
uint256 proposalId)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _proposalState[proposalId]);
}
function votingBalanceOfNow(
address account)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _getProposalState());
}
function _setProposalVals(
address account,
uint256 proposalId)
public
returns (uint256)
{
require(msg.sender == governor, "unauthorized");
require(_proposalState[proposalId].proposalTime == 0, "proposal exists");
ProposalState memory newProposal = _getProposalState();
_proposalState[proposalId] = newProposal;
return _votingBalanceOf(account, newProposal);
}
function _getProposalState()
internal
view
returns (ProposalState memory)
{
return ProposalState({
proposalTime: block.timestamp - 1,
iBZRXWeight: _calcIBZRXWeight(),
lpBZRXBalance: IERC20(BZRX).balanceOf(LPToken),
lpTotalSupply: IERC20(LPToken).totalSupply()
});
}
function _votingBalanceOf(
address account,
ProposalState memory proposal)
internal
view
returns (uint256 totalVotes)
{
uint256 _vestingLastSync = vestingLastSync[account];
if (proposal.proposalTime == 0 || _vestingLastSync > proposal.proposalTime - 1) {
return 0;
}
uint256 _vBZRXBalance = _balancesPerToken[vBZRX][account];
if (_vBZRXBalance != 0) {
// staked vBZRX is prorated based on total vested
totalVotes = _vBZRXBalance
.mul(_startingVBZRXBalance -
vestedBalanceForAmount( // overflow not possible
_startingVBZRXBalance,
0,
proposal.proposalTime
)
).div(_startingVBZRXBalance);
// user is attributed a staked balance of vested BZRX, from their last update to the present
totalVotes = vestedBalanceForAmount(
_vBZRXBalance,
_vestingLastSync,
proposal.proposalTime
).add(totalVotes);
}
totalVotes = _balancesPerToken[BZRX][account]
.add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes
.add(totalVotes);
totalVotes = _balancesPerToken[iBZRX][account]
.mul(proposal.iBZRXWeight)
.div(1e50)
.add(totalVotes);
// LPToken votes are measured based on amount of underlying BZRX staked
totalVotes = proposal.lpBZRXBalance
.mul(_balancesPerToken[LPToken][account])
.div(proposal.lpTotalSupply)
.add(totalVotes);
}
// OnlyOwner functions
function togglePause(
bool _isPaused)
external
onlyOwner
{
isPaused = _isPaused;
}
function setFundsWallet(
address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
}
function setGovernor(
address _governor)
external
onlyOwner
{
governor = _governor;
}
function setFeeTokens(
address[] calldata tokens)
external
onlyOwner
{
currentFeeTokens = tokens;
}
function setRewardPercent(
uint256 _rewardPercent)
external
onlyOwner
{
require(_rewardPercent <= 1e20, "value too high");
rewardPercent = _rewardPercent;
}
function setMaxUniswapDisagreement(
uint256 _maxUniswapDisagreement)
external
onlyOwner
{
require(_maxUniswapDisagreement != 0, "invalid param");
maxUniswapDisagreement = _maxUniswapDisagreement;
}
function setMaxCurveDisagreement(
uint256 _maxCurveDisagreement)
external
onlyOwner
{
require(_maxCurveDisagreement != 0, "invalid param");
maxCurveDisagreement = _maxCurveDisagreement;
}
function setCallerRewardDivisor(
uint256 _callerRewardDivisor)
external
onlyOwner
{
require(_callerRewardDivisor != 0, "invalid param");
callerRewardDivisor = _callerRewardDivisor;
}
function setInitialAltRewardsPerShare()
external
onlyOwner
{
uint256 index = altRewardsRounds[SUSHI].length;
if(index == 0) {
return;
}
altRewardsPerShare[SUSHI] = altRewardsRounds[SUSHI][index - 1];
}
function setBalApproval(
address _spender,
uint256 _value)
external
onlyOwner
{
IERC20(0xba100000625a3754423978a60c9317c58a424e3D).approve(_spender, _value);
}
} | Deposit to sushi masterchef | function stake(
address[] memory tokens,
uint256[] memory values
)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 stakeAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token");
stakeAmount = values[i];
if (stakeAmount == 0) {
continue;
}
uint256 pendingBefore = (token == LPToken) ? pendingSushiRewards(msg.sender) : 0;
_balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount);
_totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount);
IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount);
if (token == LPToken) {
_depositToSushiMasterchef(
IERC20(LPToken).balanceOf(address(this))
);
userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({
rewardsPerShare: altRewardsPerShare[SUSHI],
pendingRewards: pendingBefore
}
);
}
emit Stake(
msg.sender,
token,
stakeAmount
);
}
}
| 2,254,156 |
pragma solidity ^0.5.0;
/**
* The contractName contract does this and that...
*/
contract rekam_medis_pasien {
//data yang tersimpan
struct riwayat_1{
uint tinggi_badan;
uint berat_badan;
string waktu;
string penunjang;
string diagnosis;
}
struct riwayat_2{
string tatalaksana;
string tindakan;
string pelayanan_lain;
string odontogram;
string persetujuan;
}
uint256 public totalTransaksi;
mapping (uint256 => riwayat_1) public seluruh_rekam_medis_1;
mapping (uint256 => riwayat_2) public seluruh_rekam_medis_2;
//cari rekam medis siapa
mapping (uint256 => address)public pemilik;
function tambahRekamMedis(
address _addrs,
uint _tinggi_badan,
uint _berat_badan,
string memory _waktu,
string memory _penunjang,
string memory _diagnosis,
string memory _tatalaksana,
string memory _tindakan,
string memory _pelayanan_lain,
string memory _odontogram,
string memory _persetujuan
)public{
//total transaksi bertambah
totalTransaksi++;
//jumlah riwayat addrs bertambah
pemilik[totalTransaksi] = _addrs;
seluruh_rekam_medis_1[totalTransaksi] = riwayat_1(
_tinggi_badan,
_berat_badan,
_waktu,
_penunjang,
_diagnosis
);
seluruh_rekam_medis_2[totalTransaksi] = riwayat_2(
_tatalaksana,
_tindakan,
_pelayanan_lain,
_odontogram,
_persetujuan);
}
}
| total transaksi bertambahjumlah riwayat addrs bertambah | function tambahRekamMedis(
address _addrs,
uint _tinggi_badan,
uint _berat_badan,
string memory _waktu,
string memory _penunjang,
string memory _diagnosis,
string memory _tatalaksana,
string memory _tindakan,
string memory _pelayanan_lain,
string memory _odontogram,
string memory _persetujuan
)public{
totalTransaksi++;
pemilik[totalTransaksi] = _addrs;
seluruh_rekam_medis_1[totalTransaksi] = riwayat_1(
_tinggi_badan,
_berat_badan,
_waktu,
_penunjang,
_diagnosis
);
seluruh_rekam_medis_2[totalTransaksi] = riwayat_2(
_tatalaksana,
_tindakan,
_pelayanan_lain,
_odontogram,
_persetujuan);
}
| 955,886 |
./full_match/4/0xa0c032e28e06f772845B4E753aE115395c848E68/sources/contracts/ERC721Lending.sol | one NFT several times lending is available, while prev lending is ended, thus tokenId is needed. this tokenId is index for offers of collection. tokenAddress is NFTMarketplace Contract address for NFT(ERC721) assuming token transfer is approvedaddress fromOwner = tokenAddress; IERC721(tokenAddress).ownerOf(tokenId);address fromOwner = msg.sender; because parseEther's decimal is 18 , it must be divided / 1000000000; | function offerLoaningNft(address tokenAddress, uint256 tokenId, uint256 durationHours, uint256 initialWorth, uint256 earningGoal) public returns(uint256){
require(initialWorth > 0, 'Lending: Initial token worth must be above 0');
require(earningGoal > 0, 'Lending: Earning goal must be above 0');
require(durationHours > 0, 'Lending: Lending duration must be above 0');
require(lentERC721List[tokenAddress][tokenId].borrower == address(0), 'Lending: Cannot change settings, token already lent');
require(lentERC721List[tokenAddress][tokenId].lenderClaimedNFT == false, 'Lending: Loaning NFT already claimed');
NFTMarketplace nftMarketPlace = NFTMarketplace(tokenAddress);
nftMarketPlace.offerLoaningNft(tokenId, toAddress);
lentCount ++;
if(lendersWithTokens.length<=lentCount)
lendersWithTokens.push(ERC721TokenEntry(msg.sender, tokenAddress, tokenId));
else
lendersWithTokens[lentCount-1] = ERC721TokenEntry(msg.sender, tokenAddress, tokenId);
lentERC721List[tokenAddress][tokenId] = ERC721ForLend(durationHours, initialWorth/1000000000, earningGoal/1000000000, 0, msg.sender, address(0), false, 0, 0);
emit ERC721ForLendUpdated(tokenAddress, tokenId);
return lentCount;
}
| 12,435,039 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity >0.6.0;
import "../link/link.sol";
import "../IERC20/IERC20.sol";
contract tokenpeg is link {
event Refund(uint256 id, address recipient, uint256 amount, bytes reason);
event Failure(bytes reason);
event Receipt(address recipient, uint256 amount, bytes reason);
IERC20 public tokenContract;
constructor(
address[] memory _owners,
uint8 _required,
address _tokenContract
) link(_owners, _required) {
tokenContract = IERC20(_tokenContract);
}
/**
* @dev allows msg.sender to send tokens to another chain
*
* @param amount message
* @param recipient message
*/
function sendToken(uint256 amount, uint64 recipient) public {
tokenContract.burnFrom(msg.sender, amount);
bytes memory message =
abi.encodePacked(bool(true), recipient, uint64(amount), msg.sender);
pushMessage(message);
}
/**
* @dev allows msg.sender to send tokens to another chain
*
* @param amount message
* @param recipient message
*/
function mintTokens(
uint256 amount,
address recipient,
uint256 id,
bytes memory message
) internal {
bytes memory receipt = message;
try tokenContract.mint(recipient, amount) {
receipt[0] = 0x01;
} catch (bytes memory failureMessage) {
receipt[0] = 0x00;
emit Failure(failureMessage);
}
pushReceipt(id, receipt);
}
/**
* @dev on message hook, unique implementation per consumer
*
* @param _message message
*/
function onMessage(uint256 id, bytes memory _message) internal override {
//byte 0, status
//byte 1-8, eos account
//byte 9-17, amount
//byte 17-27 address
uint256 amount = readMessage(_message, 9, 8);
address recipient = address(uint160(readMessage(_message, 17, 20)));
mintTokens(amount, recipient, id, _message);
}
/**
* @dev on receipt hook, unique implementation per consumer
*
* @param _message message
*/
function onReceipt(uint256 id, bytes memory _message) internal override {
uint256 success = readMessage(_message, 0, 1);
if (success > 0) {
return;
}
uint256 amount = readMessage(_message, 9, 8);
address sender = address(uint160(readMessage(_message, 17, 20)));
tokenContract.mint(sender, amount);
emit Refund(id, sender, amount, _message);
}
}
| allows msg.sender to send tokens to another chain amount message recipient message/ | function mintTokens(
uint256 amount,
address recipient,
uint256 id,
bytes memory message
) internal {
bytes memory receipt = message;
try tokenContract.mint(recipient, amount) {
receipt[0] = 0x01;
receipt[0] = 0x00;
emit Failure(failureMessage);
}
pushReceipt(id, receipt);
}
| 12,832,546 |
// SPDX-License-Identifier: None
pragma solidity >=0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Adminable.sol";
import "./lib/Strings.sol";
import "./ModuleRegistry.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function balanceOf(uint amount) external returns (uint);
function withdraw(uint amount) external;
}
/// @title Slingshot Trading Contract
/// @author DEXAG, Inc.
/// @notice This contract serves as the entrypoint for executing
/// a Slingshot transaction on-chain.
/// @dev The specific logic for each DEX/AMM is defined within its
/// own corresponding module that is stored in the module registry.
/// Slingshot.sol references these modules to appropriately execute a trade.
/// Slingshot.sol also performs some safety checks to account for slippage
/// and security. Slingshot.sol depends on the Slingshot backend to provide
/// the details of how a given transaction will be executed within a
/// particular market.
contract Slingshot is Adminable, Strings {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public ETH_ADDRESS;
IWETH public WETH;
struct TradeFormat {
address moduleAddress;
bytes encodedCalldata;
}
ModuleRegistry public moduleRegistry;
event Trade(
address indexed user,
address fromToken,
address toToken,
uint fromAmount,
uint toAmount,
address recipient
);
event NewModuleRegistry(address oldRegistry, address newRegistry);
/// @notice Use this function for post upgrade setup
/// @param _admin Address to control admin functions
function postUpgrade(address _admin) external onlyAdminIfInitialized {
// skip when initialized
if (!isInitialized()) initialize(_admin);
// all other post upgrade setup below
}
/// @notice Initialization function for proxy setup
/// @param _admin Address to control admin functions
function initialize(address _admin) internal initializer {
initializeAdmin(_admin);
ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
/// @notice Executes multi-hop trades to get the best result
/// @param fromToken Start token address
/// @param toToken Target token address
/// @param fromAmount The initial amount of fromToken to start trading with
/// @param trades Array of encoded trades that are atomically executed
/// @param finalAmountMin The minimum expected output after all trades have been executed
/// @param recipient The address that will receive the output of a trade
function executeTrades(
address fromToken,
address toToken,
uint fromAmount,
TradeFormat[] calldata trades,
uint finalAmountMin,
address recipient
) public payable {
uint initialBalance = _getTokenBalance(toToken);
_transferFromOrWrap(fromToken, _msgSender(), fromAmount);
// Checks to make sure that module exists and is correct
for(uint i = 0; i < trades.length; i++) {
require(moduleRegistry.isModule(trades[i].moduleAddress), "Slingshot: not a module");
// delagatecall message is made on module contract, which is trusted
(bool success, bytes memory data) = trades[i].moduleAddress.delegatecall(trades[i].encodedCalldata);
require(success, appendString(prependNumber(i, ", Slingshot: swap failed: "), string(data)));
}
uint finalBalance = _getTokenBalance(toToken);
uint finalAmount = finalBalance.sub(initialBalance);
require(finalAmount >= finalAmountMin, "Slingshot: result is lower than required min");
// Send to recipient address. Generally expected to be msg.sender, but can also be defined by user.
// This allows for more flexibility, but isn't necessary.
_sendFunds(toToken, recipient, finalAmount);
emit Trade(_msgSender(), fromToken, toToken, fromAmount, finalAmount, recipient);
}
/// @notice Sets module registry used to verify modules
/// @param _moduleRegistry The address of module registry
function setModuleRegistry(address _moduleRegistry) external onlyAdmin {
address oldRegistry = address(moduleRegistry);
moduleRegistry = ModuleRegistry(_moduleRegistry);
emit NewModuleRegistry(oldRegistry, _moduleRegistry);
}
/// @notice In an unlikely scenario of tokens being send to this contract
/// allow adming to rescue them.
/// @param token The address of the token to rescue
/// @param to The address of recipient
/// @param amount The amount of the token to rescue
function rescueTokens(address token, address to, uint amount) external onlyAdmin {
if (token == ETH_ADDRESS) {
(bool success, ) = to.call{value: amount}("");
require(success, "Slingshot: ETH rescue failed.");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
/// @notice Transfer tokens from sender to this contract or wraps ETH
/// @param fromToken The address of the token
/// @param from The address of sender that provides token
/// @param amount The amount of the token to transfer
function _transferFromOrWrap(address fromToken, address from, uint amount) internal {
// transfer tokens or wrap ETH
if (fromToken == ETH_ADDRESS) {
require(msg.value == amount, "Slingshot: incorect ETH value");
WETH.deposit{value: amount}();
} else {
require(msg.value == 0, "Slingshot: should not send ETH");
IERC20(fromToken).safeTransferFrom(from, address(this), amount);
}
}
/// @notice Returns balancer of the token
/// @param token The address of the token
/// @return balance of the token, defaults to WETH for ETH
function _getTokenBalance(address token) internal view returns (uint) {
if (token == ETH_ADDRESS) {
return WETH.balanceOf(address(this));
} else {
return IERC20(token).balanceOf(address(this));
}
}
/// @notice Sends token funds. For ETH, it unwraps WETH
/// @param token The address of the token to send
/// @param to The address of recipient
/// @param amount The amount of the token to send
function _sendFunds(address token, address to, uint amount) internal {
if (token == ETH_ADDRESS) {
WETH.withdraw(amount);
(bool success, ) = to.call{value: amount}("");
require(success, "Slingshot: ETH Transfer failed.");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
receive() external payable {}
}
| Executes multi-hop trades to get the best result fromToken Start token address toToken Target token address fromAmount The initial amount of fromToken to start trading with trades Array of encoded trades that are atomically executed finalAmountMin The minimum expected output after all trades have been executed recipient The address that will receive the output of a trade Checks to make sure that module exists and is correct delagatecall message is made on module contract, which is trusted | function executeTrades(
address fromToken,
address toToken,
uint fromAmount,
TradeFormat[] calldata trades,
uint finalAmountMin,
address recipient
) public payable {
uint initialBalance = _getTokenBalance(toToken);
_transferFromOrWrap(fromToken, _msgSender(), fromAmount);
for(uint i = 0; i < trades.length; i++) {
require(moduleRegistry.isModule(trades[i].moduleAddress), "Slingshot: not a module");
(bool success, bytes memory data) = trades[i].moduleAddress.delegatecall(trades[i].encodedCalldata);
require(success, appendString(prependNumber(i, ", Slingshot: swap failed: "), string(data)));
}
uint finalBalance = _getTokenBalance(toToken);
uint finalAmount = finalBalance.sub(initialBalance);
require(finalAmount >= finalAmountMin, "Slingshot: result is lower than required min");
emit Trade(_msgSender(), fromToken, toToken, fromAmount, finalAmount, recipient);
}
| 5,464,467 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title BurnerRole Contract
/// @notice Only administrators can update the burner roles
/// @dev Keeps track of burners and can check if an account is authorized
contract BurnerRole is OwnerRole {
event BurnerAdded(address indexed addedBurner, address indexed addedBy);
event BurnerRemoved(
address indexed removedBurner,
address indexed removedBy
);
Role private _burners;
/// @dev Modifier to make a function callable only when the caller is a burner
modifier onlyBurner() {
require(
isBurner(msg.sender),
"BurnerRole: caller does not have the Burner role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a burner role
function isBurner(address account) public view returns (bool) {
return _has(_burners, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a burner
/// @param account The address that is guaranteed burner authorization
function _addBurner(address account) internal {
_add(_burners, account);
emit BurnerAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a burner
/// @param account The address removed as a burner
function _removeBurner(address account) internal {
_remove(_burners, account);
emit BurnerRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a burner
/// @param account The address that is guaranteed burner authorization
function addBurner(address account) external onlyOwner {
_addBurner(account);
}
/// @dev Public function that removes an account from being a burner
/// @param account The address removed as a burner
function removeBurner(address account) external onlyOwner {
_removeBurner(account);
}
uint256[49] private __gap;
}
| Only administrators should be allowed to update this Adds an address as a burner account The address that is guaranteed burner authorization | function _addBurner(address account) internal {
_add(_burners, account);
emit BurnerAdded(account, msg.sender);
}
| 5,361,958 |
./full_match/80001/0xd6dA095745B22232BE1a8c7a35B7e29247421826/sources/contracts/OreSmelting.sol | First, burn the access keys from the user's wallet here we can add other conditions to the amount that can be claimed Use the rest of the inherited claim function logic | function _transferTokensOnClaim(
address _receiver,
uint256 _tokenId,
uint256 _quantity
) internal override {
oreNftCollection.burn(
);
super._transferTokensOnClaim(_receiver, _tokenId, _quantity);
}
| 5,650,067 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import "./Common.sol";
import "./Merkle.sol";
import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol";
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
/**
* @title Replica
* @author Celo Labs Inc.
* @notice Contract responsible for tracking root updates on home,
* and dispatching messages on Replica to end recipients.
*/
contract Replica is Common {
using QueueLib for QueueLib.Queue;
using MerkleLib for MerkleLib.Tree;
using TypedMemView for bytes;
using TypedMemView for bytes29;
using Message for bytes29;
/// @notice Status of message
enum MessageStatus {
None,
Pending,
Processed
}
event ProcessSuccess(bytes32 indexed messageHash);
event ProcessError(
bytes32 indexed messageHash,
uint32 indexed sequence,
address indexed recipient,
bytes returnData
);
/// @notice Minimum gas for message processing
uint256 public constant PROCESS_GAS = 850000;
/// @notice Reserved gas (to ensure tx completes in case message processing runs out)
uint256 public constant RESERVE_GAS = 15000;
/// @notice Domain of home chain
uint32 public remoteDomain;
/// @notice Number of seconds to wait before enqueued root becomes confirmable
uint256 public optimisticSeconds;
/// @notice Index of last processed message's leaf in home's merkle tree
uint32 public nextToProcess;
/// @notice Mapping of enqueued roots to allowable confirmation times
mapping(bytes32 => uint256) public confirmAt;
/// @dev re-entrancy guard
uint8 private entered;
/// @notice Mapping of message leaves to MessageStatus
mapping(bytes32 => MessageStatus) public messages;
uint256[44] private __GAP; // gap for upgrade safety
constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks
function acceptableRoot(bytes32 _root) public view returns (bool) {
uint256 _time = confirmAt[_root];
if (_time == 0) {
return false;
}
return block.timestamp >= _time;
}
function initialize(
uint32 _remoteDomain,
address _updater,
bytes32 _current,
uint256 _optimisticSeconds,
uint32 _nextToProcess
) public initializer {
__Common_initialize(_updater);
entered = 1;
remoteDomain = _remoteDomain;
current = _current;
confirmAt[_current] = 1;
optimisticSeconds = _optimisticSeconds;
nextToProcess = _nextToProcess;
}
/**
* @notice Called by external agent. Enqueues signed update's new root,
* marks root's allowable confirmation time, and emits an `Update` event.
* @dev Reverts if update doesn't build off queue's last root or replica's
* current root if queue is empty. Also reverts if signature is invalid.
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Updater's signature on `_oldRoot` and `_newRoot`
**/
function update(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
if (queue.length() > 0) {
require(_oldRoot == queue.lastItem(), "not end of queue");
} else {
require(current == _oldRoot, "not current update");
}
require(
Common._isUpdaterSignature(_oldRoot, _newRoot, _signature),
"bad sig"
);
// Hook for future use
_beforeUpdate();
// Set the new root's confirmation timer
// And add the new root to the queue of roots
confirmAt[_newRoot] = block.timestamp + optimisticSeconds;
queue.enqueue(_newRoot);
emit Update(remoteDomain, _oldRoot, _newRoot, _signature);
}
/**
* @notice Called by external agent. Confirms as many confirmable roots in
* queue as possible, updating replica's current root to be the last
* confirmed root.
* @dev Reverts if queue started as empty (i.e. no roots to confirm)
**/
function confirm() external notFailed {
require(queue.length() != 0, "!pending");
bytes32 _pending;
// Traverse the queue by peeking each iterm to see if it ought to be
// confirmed. If so, dequeue it
uint256 _remaining = queue.length();
while (_remaining > 0 && acceptableRoot(queue.peek())) {
_pending = queue.dequeue();
_remaining -= 1;
}
// This condition is hit if the while loop is never executed, because
// the first queue item has not hit its timer yet
require(_pending != bytes32(0), "!time");
_beforeConfirm();
current = _pending;
}
/**
* @notice First attempts to prove the validity of provided formatted
* `message`. If the message is successfully proven, then tries to process
* message.
* @dev Reverts if `prove` call returns false
* @param _message Formatted message (refer to Common.sol Message library)
* @param _proof Merkle proof of inclusion for message's leaf
* @param _index Index of leaf in home's merkle tree
**/
function proveAndProcess(
bytes memory _message,
bytes32[32] calldata _proof,
uint256 _index
) external {
require(prove(keccak256(_message), _proof, _index), "!prove");
process(_message);
}
/**
* @notice Called by external agent. Returns next pending root to be
* confirmed and its confirmation time. If queue is empty, returns null
* values.
* @return _pending Pending (unconfirmed) root
* @return _confirmAt Pending root's confirmation time
**/
function nextPending()
external
view
returns (bytes32 _pending, uint256 _confirmAt)
{
if (queue.length() != 0) {
_pending = queue.peek();
_confirmAt = confirmAt[_pending];
} else {
_pending = current;
_confirmAt = confirmAt[current];
}
}
/**
* @notice Called by external agent. Returns true if there is a confirmable
* root in the queue and false if otherwise.
**/
function canConfirm() external view returns (bool) {
return queue.length() != 0 && acceptableRoot(queue.peek());
}
/**
* @notice Given formatted message, attempts to dispatch message payload to
* end recipient.
* @dev Requires recipient to have implemented `handle` method (refer to
* XAppConnectionManager.sol). Reverts if formatted message's destination domain
* doesn't match replica's own domain, if message is out of order (skips
* one or more sequence numbers), if message has not been proven (doesn't
* have MessageStatus.Pending), or if not enough gas is provided for
* dispatch transaction.
* @param _message Formatted message (refer to Common.sol Message library)
* @return _success True if dispatch transaction succeeded (false if
* otherwise)
**/
function process(bytes memory _message) public returns (bool _success) {
bytes29 _m = _message.ref(0);
bytes32 _messageHash = _m.keccak();
uint32 _sequence = _m.sequence();
require(_m.destination() == localDomain, "!destination");
require(messages[_messageHash] == MessageStatus.Pending, "!pending");
require(entered == 1, "!reentrant");
entered = 0;
// update the status and next to process
messages[_messageHash] = MessageStatus.Processed;
nextToProcess = _sequence + 1;
// NB:
// A call running out of gas TYPICALLY errors the whole tx. We want to
// a) ensure the call has a sufficient amount of gas to make a
// meaningful state change.
// b) ensure that if the subcall runs out of gas, that the tx as a whole
// does not revert (i.e. we still mark the message processed)
// To do this, we require that we have enough gas to process
// and still return. We then delegate only the minimum processing gas.
require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas");
// transparently return.
address _recipient = _m.recipientAddress();
bytes memory _returnData;
(_success, _returnData) = _recipient.call{gas: PROCESS_GAS}(
abi.encodeWithSignature(
"handle(uint32,bytes32,bytes)",
_m.origin(),
_m.sender(),
_m.body().clone()
)
);
if (_success) {
emit ProcessSuccess(_messageHash);
} else {
emit ProcessError(_messageHash, _sequence, _recipient, _returnData);
}
entered = 1;
}
/**
* @notice Attempts to prove the validity of message given its leaf, the
* merkle proof of inclusion for the leaf, and the index of the leaf.
* @dev Reverts if message's MessageStatus != None (i.e. if message was
* already proven or processed)
* @param _leaf Leaf of message to prove
* @param _proof Merkle proof of inclusion for leaf
* @param _index Index of leaf in home's merkle tree
* @return Returns true if proof was valid and `prove` call succeeded
**/
function prove(
bytes32 _leaf,
bytes32[32] calldata _proof,
uint256 _index
) public returns (bool) {
require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None");
bytes32 _actual = MerkleLib.branchRoot(_leaf, _proof, _index);
// NB:
// For convenience, we allow proving against any previous root.
// This means that witnesses never need to be updated for the new root
if (acceptableRoot(_actual)) {
messages[_leaf] = MessageStatus.Pending;
return true;
}
return false;
}
/// @notice Hash of Home's domain concatenated with "OPTICS"
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(remoteDomain);
}
/// @notice Sets contract state to FAILED
function _fail() internal override {
_setFailed();
}
/// @notice Hook for potential future use
// solhint-disable-next-line no-empty-blocks
function _beforeConfirm() internal {}
/// @notice Hook for potential future use
// solhint-disable-next-line no-empty-blocks
function _beforeUpdate() internal {}
}
| Attempts to prove the validity of message given its leaf, the merkle proof of inclusion for the leaf, and the index of the leaf. Reverts if message's MessageStatus != None (i.e. if message was already proven or processed) _leaf Leaf of message to prove _proof Merkle proof of inclusion for leaf _index Index of leaf in home's merkle tree return Returns true if proof was valid and `prove` call succeeded/ NB: For convenience, we allow proving against any previous root. This means that witnesses never need to be updated for the new root | function prove(
bytes32 _leaf,
bytes32[32] calldata _proof,
uint256 _index
) public returns (bool) {
require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None");
bytes32 _actual = MerkleLib.branchRoot(_leaf, _proof, _index);
if (acceptableRoot(_actual)) {
messages[_leaf] = MessageStatus.Pending;
return true;
}
return false;
}
| 1,038,389 |
pragma solidity ^0.4.23;
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title Ownable
* 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;
// The Ownable constructor sets the original `owner`
// of the contract to the sender account.
constructor() public {
owner = msg.sender;
}
// Throw if called by any account other than the current owner
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allow the current owner to transfer control of the contract to a newOwner
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract RAcoinToken is Ownable, ERC20Interface {
string public constant symbol = "RAC";
string public constant name = "RAcoinToken";
uint private _totalSupply;
uint public constant decimals = 18;
uint private unmintedTokens = 20000000000*uint(10)**decimals;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
//Struct to hold lockup records
struct LockupRecord {
uint amount;
uint unlockTime;
}
// Balances for each account
mapping(address => uint) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint)) allowed;
// Balances for lockup accounts
mapping(address => LockupRecord)balancesLockup;
/**
====== JACKPOT IMPLEMENTATION ======
*/
// Percentage for jackpot reserving during tokens transfer
uint public reservingPercentage = 1;
// Minimum amount of jackpot, before reaching it jackpot cannot be distributed.
// Default value is 100,000 RAC
uint public jackpotMinimumAmount = 100000 * uint(10)**decimals;
// reservingStep is used for calculating how many times a user will be added to jackpot participants list:
// times user will be added to jackpotParticipants list = transfer amount / reservingStep
// the more user transfer tokens using transferWithReserving function the more times he will be added and,
// as a result, more chances to win the jackpot. Default value is 10,000 RAC
uint public reservingStep = 10000 * uint(10)**decimals;
// The seed is used each time Jackpot is distributing for generating a random number.
// First seed has some value, after the every turn of the jackpot distribution will be changed
uint private seed = 1; // Default seed
// The maximum allowed times when jackpot amount and distribution time will be set by owner,
// Used only for token sale jackpot distribution
int public maxAllowedManualDistribution = 111;
// Either or not clear the jackpot participants list after the Jackpot distribution
bool public clearJackpotParticipantsAfterDistribution = false;
// Variable that holds last actual index of jackpotParticipants collection
uint private index = 0;
// The list with Jackpot participants. The more times address is in the list, the more chances to win the Jackpot
address[] private jackpotParticipants;
event SetReservingPercentage(uint _value);
event SetReservingStep(uint _value);
event SetJackpotMinimumAmount(uint _value);
event AddAddressToJackpotParticipants(address indexed _sender, uint _times);
//Setting the reservingPercentage value, allowed only for owner
function setReservingPercentage(uint _value) public onlyOwner returns (bool success) {
assert(_value > 0 && _value < 100);
reservingPercentage = _value;
emit SetReservingPercentage(_value);
return true;
}
//Setting the reservingStep value, allowed only for owner
function setReservingStep(uint _value) public onlyOwner returns (bool success) {
assert(_value > 0);
reservingStep = _value;
emit SetReservingStep(_value);
return true;
}
//Setting the setJackpotMinimumAmount value, allowed only for owner
function setJackpotMinimumAmount(uint _value) public onlyOwner returns (bool success) {
jackpotMinimumAmount = _value;
emit SetJackpotMinimumAmount(_value);
return true;
}
//Setting the clearJackpotParticipantsAfterDistribution value, allowed only for owner
function setPoliticsForJackpotParticipantsList(bool _clearAfterDistribution) public onlyOwner returns (bool success) {
clearJackpotParticipantsAfterDistribution = _clearAfterDistribution;
return true;
}
// Empty the jackpot participants list
function clearJackpotParticipants() public onlyOwner returns (bool success) {
index = 0;
return true;
}
// Using this function a user transfers tokens and participates in operating jackpot
// User sets the total transfer amount that includes the Jackpot reserving deposit
function transferWithReserving(address _to, uint _totalTransfer) public returns (bool success) {
uint netTransfer = _totalTransfer * (100 - reservingPercentage) / 100;
require(balances[msg.sender] >= _totalTransfer && (_totalTransfer > netTransfer));
if (transferMain(msg.sender, _to, netTransfer) && (_totalTransfer >= reservingStep)) {
processJackpotDeposit(_totalTransfer, netTransfer, msg.sender);
}
return true;
}
// Using this function a user transfers tokens and participates in operating jackpot
// User sets the net value of transfer without the Jackpot reserving deposit amount
function transferWithReservingNet(address _to, uint _netTransfer) public returns (bool success) {
uint totalTransfer = _netTransfer * (100 + reservingPercentage) / 100;
require(balances[msg.sender] >= totalTransfer && (totalTransfer > _netTransfer));
if (transferMain(msg.sender, _to, _netTransfer) && (totalTransfer >= reservingStep)) {
processJackpotDeposit(totalTransfer, _netTransfer, msg.sender);
}
return true;
}
// Using this function a spender transfers tokens and make an owner of funds a participant of the operating Jackpot
// User sets the total transfer amount that includes the Jackpot reserving deposit
function transferFromWithReserving(address _from, address _to, uint _totalTransfer) public returns (bool success) {
uint netTransfer = _totalTransfer * (100 - reservingPercentage) / 100;
require(balances[_from] >= _totalTransfer && (_totalTransfer > netTransfer));
if (transferFrom(_from, _to, netTransfer) && (_totalTransfer >= reservingStep)) {
processJackpotDeposit(_totalTransfer, netTransfer, _from);
}
return true;
}
// Using this function a spender transfers tokens and make an owner of funds a participatants of the operating Jackpot
// User set the net value of transfer without the Jackpot reserving deposit amount
function transferFromWithReservingNet(address _from, address _to, uint _netTransfer) public returns (bool success) {
uint totalTransfer = _netTransfer * (100 + reservingPercentage) / 100;
require(balances[_from] >= totalTransfer && (totalTransfer > _netTransfer));
if (transferFrom(_from, _to, _netTransfer) && (totalTransfer >= reservingStep)) {
processJackpotDeposit(totalTransfer, _netTransfer, _from);
}
return true;
}
// Withdraw deposit of Jackpot amount and add address to Jackpot Participants List according to transaction amount
function processJackpotDeposit(uint _totalTransfer, uint _netTransfer, address _participant) private returns (bool success) {
addAddressToJackpotParticipants(_participant, _totalTransfer);
uint jackpotDeposit = _totalTransfer - _netTransfer;
balances[_participant] -= jackpotDeposit;
balances[0] += jackpotDeposit;
emit Transfer(_participant, 0, jackpotDeposit);
return true;
}
// Add address to Jackpot Participants List
function addAddressToJackpotParticipants(address _participant, uint _transactionAmount) private returns (bool success) {
uint timesToAdd = _transactionAmount / reservingStep;
for (uint i = 0; i < timesToAdd; i++){
if(index == jackpotParticipants.length) {
jackpotParticipants.length += 1;
}
jackpotParticipants[index++] = _participant;
}
emit AddAddressToJackpotParticipants(_participant, timesToAdd);
return true;
}
// Distribute jackpot. For finding a winner we use random number that is produced by multiplying a previous seed
// received from previous jackpot distribution and casted to uint last available block hash.
// Remainder from the received random number and total number of participants will give an index of a winner in the Jackpot participants list
function distributeJackpot(uint _nextSeed) public onlyOwner returns (bool success) {
assert(balances[0] >= jackpotMinimumAmount);
assert(_nextSeed > 0);
uint additionalSeed = uint(blockhash(block.number - 1));
uint rnd = 0;
while(rnd < index) {
rnd += additionalSeed * seed;
}
uint winner = rnd % index;
balances[jackpotParticipants[winner]] += balances[0];
emit Transfer(0, jackpotParticipants[winner], balances[0]);
balances[0] = 0;
seed = _nextSeed;
if (clearJackpotParticipantsAfterDistribution) {
clearJackpotParticipants();
}
return true;
}
// Distribute Token Sale Jackpot by minting token sale jackpot directly to 0x0 address and calling distributeJackpot function
function distributeTokenSaleJackpot(uint _nextSeed, uint _amount) public onlyOwner returns (bool success) {
require (maxAllowedManualDistribution > 0);
if (mintTokens(0, _amount) && distributeJackpot(_nextSeed)) {
maxAllowedManualDistribution--;
}
return true;
}
/**
====== ERC20 IMPLEMENTATION ======
*/
// Return total supply of tokens including locked-up funds and current Jackpot deposit
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// Get the balance of the specified address
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
// Transfer token to a specified address
function transfer(address _to, uint _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
return transferMain(msg.sender, _to, _value);
}
// Transfer tokens from one address to another
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
if (transferMain(_from, _to, _value)){
allowed[_from][msg.sender] -= _value;
return true;
} else {
return false;
}
}
// Main transfer function. Checking of balances is made in calling function
function transferMain(address _from, address _to, uint _value) private returns (bool success) {
require(_to != address(0));
assert(balances[_to] + _value >= balances[_to]);
balances[_from] -= _value;
balances[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// Function to check the amount of tokens than an owner allowed to a spender
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
/**
====== LOCK-UP IMPLEMENTATION ======
*/
function unlockOwnFunds() public returns (bool success) {
return unlockFunds(msg.sender);
}
function unlockSupervisedFunds(address _from) public onlyOwner returns (bool success) {
return unlockFunds(_from);
}
function unlockFunds(address _owner) private returns (bool success) {
require(balancesLockup[_owner].unlockTime < now && balancesLockup[_owner].amount > 0);
balances[_owner] += balancesLockup[_owner].amount;
emit Transfer(_owner, _owner, balancesLockup[_owner].amount);
balancesLockup[_owner].amount = 0;
return true;
}
function balanceOfLockup(address _owner) public view returns (uint balance, uint unlockTime) {
return (balancesLockup[_owner].amount, balancesLockup[_owner].unlockTime);
}
/**
====== TOKENS MINTING IMPLEMENTATION ======
*/
// Mint RAcoin tokens. No more than 20,000,000,000 RAC can be minted
function mintTokens(address _target, uint _mintedAmount) public onlyOwner returns (bool success) {
require(_mintedAmount <= unmintedTokens);
balances[_target] += _mintedAmount;
unmintedTokens -= _mintedAmount;
_totalSupply += _mintedAmount;
emit Transfer(1, _target, _mintedAmount);
return true;
}
// Mint RAcoin locked-up tokens
// Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintLockupTokens(address _target, uint _mintedAmount, uint _unlockTime) public onlyOwner returns (bool success) {
require(_mintedAmount <= unmintedTokens);
balancesLockup[_target].amount += _mintedAmount;
balancesLockup[_target].unlockTime = _unlockTime;
unmintedTokens -= _mintedAmount;
_totalSupply += _mintedAmount;
emit Transfer(1, _target, _mintedAmount); //TODO
return true;
}
// Mint RAcoin tokens for token sale participants and add them to Jackpot list
// Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintTokensWithIncludingInJackpot(address _target, uint _mintedAmount) public onlyOwner returns (bool success) {
require(maxAllowedManualDistribution > 0);
if (mintTokens(_target, _mintedAmount)) {
addAddressToJackpotParticipants(_target, _mintedAmount);
}
return true;
}
// Mint RAcoin tokens and approve the passed address to spend the minted amount of tokens
// Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintTokensWithApproval(address _target, uint _mintedAmount, address _spender) public onlyOwner returns (bool success) {
require(_mintedAmount <= unmintedTokens);
balances[_target] += _mintedAmount;
unmintedTokens -= _mintedAmount;
_totalSupply += _mintedAmount;
allowed[_target][_spender] += _mintedAmount;
emit Transfer(1, _target, _mintedAmount);
return true;
}
// After firing this function no more tokens can be created
function stopTokenMinting() public onlyOwner returns (bool success) {
unmintedTokens = 0;
return true;
}
} | Transfer token to a specified address | function transfer(address _to, uint _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
return transferMain(msg.sender, _to, _value);
}
| 7,952,846 |
pragma solidity 0.6.6;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "../apis/uniswap/IUniswapV2Router02.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IWorker.sol";
import "../interfaces/IPancakeMasterChef.sol";
import "../../utils/AlpacaMath.sol";
import "../../utils/SafeToken.sol";
contract PancakeswapWorker is OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe, IWorker {
/// @notice Libraries
using SafeToken for address;
using SafeMath for uint256;
/// @notice Events
event Reinvest(address indexed caller, uint256 reward, uint256 bounty);
event AddShare(uint256 indexed id, uint256 share);
event RemoveShare(uint256 indexed id, uint256 share);
event Liquidate(uint256 indexed id, uint256 wad);
/// @notice Immutable variables
IPancakeMasterChef public masterChef;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
IUniswapV2Pair public lpToken;
address public wNative;
address public baseToken;
address public quoteToken;
address public cake;
address public operator;
uint256 public pid;
/// @notice Mutable state variables
mapping(uint256 => uint256) public shares;
mapping(address => bool) public okStrats;
uint256 public totalShare;
IStrategy public addStrat;
IStrategy public liqStrat;
uint256 public reinvestBountyBps;
function initialize(
address _operator,
address _baseToken,
IPancakeMasterChef _masterChef,
IUniswapV2Router02 _router,
uint256 _pid,
IStrategy _addStrat,
IStrategy _liqStrat,
uint256 _reinvestBountyBps
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init();
operator = _operator;
baseToken = _baseToken;
wNative = _router.WETH();
masterChef = _masterChef;
router = _router;
factory = IUniswapV2Factory(_router.factory());
// Get lpToken and quoteToken from MasterChef pool
pid = _pid;
(IERC20 _lpToken, , , ) = masterChef.poolInfo(_pid);
lpToken = IUniswapV2Pair(address(_lpToken));
address token0 = lpToken.token0();
address token1 = lpToken.token1();
quoteToken = token0 == baseToken ? token1 : token0;
cake = address(masterChef.cake());
addStrat = _addStrat;
liqStrat = _liqStrat;
okStrats[address(addStrat)] = true;
okStrats[address(liqStrat)] = true;
reinvestBountyBps = _reinvestBountyBps;
lpToken.approve(address(_masterChef), uint256(-1)); // 100% trust in the staking pool
lpToken.approve(address(router), uint256(-1)); // 100% trust in the router
quoteToken.safeApprove(address(router), uint256(-1)); // 100% trust in the router
cake.safeApprove(address(router), uint256(-1)); // 100% trust in the router
}
/// @dev Require that the caller must be an EOA account to avoid flash loans.
modifier onlyEOA() {
require(msg.sender == tx.origin, "not eoa");
_;
}
/// @dev Require that the caller must be the operator (the bank).
modifier onlyOperator() {
require(msg.sender == operator, "not operator");
_;
}
/// @dev Return the entitied LP token balance for the given shares.
/// @param share The number of shares to be converted to LP balance.
function shareToBalance(uint256 share) public view returns (uint256) {
if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.
(uint256 totalBalance, ) = masterChef.userInfo(pid, address(this));
return share.mul(totalBalance).div(totalShare);
}
/// @dev Return the number of shares to receive if staking the given LP tokens.
/// @param balance the number of LP tokens to be converted to shares.
function balanceToShare(uint256 balance) public view returns (uint256) {
if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.
(uint256 totalBalance, ) = masterChef.userInfo(pid, address(this));
return balance.mul(totalShare).div(totalBalance);
}
/// @dev Re-invest whatever this worker has earned back to staked LP tokens.
function reinvest() public override onlyEOA nonReentrant {
// 1. Withdraw all the rewards.
masterChef.withdraw(pid, 0);
uint256 reward = cake.balanceOf(address(this));
if (reward == 0) return;
// 2. Send the reward bounty to the caller.
uint256 bounty = reward.mul(reinvestBountyBps) / 10000;
cake.safeTransfer(msg.sender, bounty);
// 3. Convert all the remaining rewards to BaseToken via Native for liquidity.
address[] memory path;
if (baseToken == wNative) {
path = new address[](2);
path[0] = address(cake);
path[1] = address(wNative);
} else {
path = new address[](3);
path[0] = address(cake);
path[1] = address(wNative);
path[2] = address(baseToken);
}
router.swapExactTokensForTokens(reward.sub(bounty), 0, path, address(this), now);
// 4. Use add Token strategy to convert all BaseToken to LP tokens.
baseToken.safeTransfer(address(addStrat), baseToken.myBalance());
addStrat.execute(address(0), 0, abi.encode(baseToken, quoteToken, 0));
// 5. Mint more LP tokens and stake them for more rewards.
masterChef.deposit(pid, lpToken.balanceOf(address(this)));
emit Reinvest(msg.sender, reward, bounty);
}
/// @dev Work on the given position. Must be called by the operator.
/// @param id The position ID to work on.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy address and calldata.
function work(uint256 id, address user, uint256 debt, bytes calldata data)
override
external
onlyOperator nonReentrant
{
// 1. Convert this position back to LP tokens.
_removeShare(id);
// 2. Perform the worker strategy; sending LP tokens + BaseToken; expecting LP tokens + BaseToken.
(address strat, bytes memory ext) = abi.decode(data, (address, bytes));
require(okStrats[strat], "unapproved work strategy");
lpToken.transfer(strat, lpToken.balanceOf(address(this)));
baseToken.safeTransfer(strat, baseToken.myBalance());
IStrategy(strat).execute(user, debt, ext);
// 3. Add LP tokens back to the farming pool.
_addShare(id);
// 4. Return any remaining BaseToken back to the operator.
baseToken.safeTransfer(msg.sender, baseToken.myBalance());
}
/// @dev Return maximum output given the input amount and the status of Uniswap reserves.
/// @param aIn The amount of asset to market sell.
/// @param rIn the amount of asset in reserve for input.
/// @param rOut The amount of asset in reserve for output.
function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) {
if (aIn == 0) return 0;
require(rIn > 0 && rOut > 0, "bad reserve values");
uint256 aInWithFee = aIn.mul(997);
uint256 numerator = aInWithFee.mul(rOut);
uint256 denominator = rIn.mul(1000).add(aInWithFee);
return numerator / denominator;
}
/// @dev Return the amount of BaseToken to receive if we are to liquidate the given position.
/// @param id The position ID to perform health check.
function health(uint256 id) external override view returns (uint256) {
// 1. Get the position's LP balance and LP total supply.
uint256 lpBalance = shareToBalance(shares[id]);
uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant
// 2. Get the pool's total supply of BaseToken and QuoteToken.
(uint256 r0, uint256 r1,) = lpToken.getReserves();
(uint256 totalBaseToken, uint256 totalQuoteToken) = lpToken.token0() == baseToken ? (r0, r1) : (r1, r0);
// 3. Convert the position's LP tokens to the underlying assets.
uint256 userBaseToken = lpBalance.mul(totalBaseToken).div(lpSupply);
uint256 userQuoteToken = lpBalance.mul(totalQuoteToken).div(lpSupply);
// 4. Convert all QuoteToken to BaseToken and return total BaseToken.
return getMktSellAmount(
userQuoteToken, totalQuoteToken.sub(userQuoteToken), totalBaseToken.sub(userBaseToken)
).add(userBaseToken);
}
/// @dev Liquidate the given position by converting it to BaseToken and return back to caller.
/// @param id The position ID to perform liquidation
function liquidate(uint256 id) external override onlyOperator nonReentrant {
// 1. Convert the position back to LP tokens and use liquidate strategy.
_removeShare(id);
lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));
liqStrat.execute(address(0), 0, abi.encode(baseToken, quoteToken, 0));
// 2. Return all available BaseToken back to the operator.
uint256 wad = baseToken.myBalance();
baseToken.safeTransfer(msg.sender, wad);
emit Liquidate(id, wad);
}
/// @dev Internal function to stake all outstanding LP tokens to the given position ID.
function _addShare(uint256 id) internal {
uint256 balance = lpToken.balanceOf(address(this));
if (balance > 0) {
uint256 share = balanceToShare(balance);
masterChef.deposit(pid, balance);
shares[id] = shares[id].add(share);
totalShare = totalShare.add(share);
emit AddShare(id, share);
}
}
/// @dev Internal function to remove shares of the ID and convert to outstanding LP tokens.
function _removeShare(uint256 id) internal {
uint256 share = shares[id];
if (share > 0) {
uint256 balance = shareToBalance(share);
masterChef.withdraw(pid, balance);
totalShare = totalShare.sub(share);
shares[id] = 0;
emit RemoveShare(id, share);
}
}
/// @dev Set the reward bounty for calling reinvest operations.
/// @param _reinvestBountyBps The bounty value to update.
function setReinvestBountyBps(uint256 _reinvestBountyBps) external onlyOwner {
reinvestBountyBps = _reinvestBountyBps;
}
/// @dev Set the given strategies' approval status.
/// @param strats The strategy addresses.
/// @param isOk Whether to approve or unapprove the given strategies.
function setStrategyOk(address[] calldata strats, bool isOk) external override onlyOwner {
uint256 len = strats.length;
for (uint256 idx = 0; idx < len; idx++) {
okStrats[strats[idx]] = isOk;
}
}
/// @dev Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds.
/// @param _addStrat The new add strategy contract.
/// @param _liqStrat The new liquidate strategy contract.
function setCriticalStrategies(IStrategy _addStrat, IStrategy _liqStrat) external onlyOwner {
addStrat = _addStrat;
liqStrat = _liqStrat;
}
receive() external payable {}
}
| Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds. _addStrat The new add strategy contract. _liqStrat The new liquidate strategy contract. | function setCriticalStrategies(IStrategy _addStrat, IStrategy _liqStrat) external onlyOwner {
addStrat = _addStrat;
liqStrat = _liqStrat;
}
| 1,803,110 |
./full_match/137/0xBC225699c4899CF85894902CD947BDc02b42d610/sources/UExchangeRouter02.sol | SWAP requires the initial amount to have already been sent to the first pair | function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UExchangeLibrary.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UExchangeLibrary.pairFor(factory, output, path[i + 2]) : _to;
IUExchangePair(UExchangeLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
| 4,758,423 |
./full_match/1/0x1bB602b7a2ef2aECBA8FE3Df4b501C4C567B697d/sources/lib/ERC721A/contracts/ERC721A.sol | Returns the packed ownership data of `tokenId`./ If not burned. Invariant: There will always be an initialized ownership slot (i.e. `ownership.addr != address(0) && ownership.burned == false`) before an unintialized ownership slot (i.e. `ownership.addr == address(0) && ownership.burned == false`) Hence, `curr` will not underflow. We can directly compare the packed value. If the address is zero, packed will be zero. | function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr) {
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
if (packed & _BITMASK_BURNED == 0) {
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
| 2,948,497 |
./partial_match/1/0x0cC7981b0D2c3578C4C6Fb6B8312f40104953769/sources/MUSKTRIPS.sol | Declare the customMin function | function customMin(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
address payable private _taxWallet;
| 9,262,552 |
./partial_match/1/0x0160fB79E65bEC0f16D750098951C26950ADc5Ed/sources/OpenZeppelinOwnableAndERC721.sol | Initializes the contract setting the deployer as the initial owner./ | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
constructor() {
_transferOwnership(_msgSender());
}
| 2,744,491 |
./full_match/4/0x12f20E573d11Acad3bFdc95d84Ce15c58575685d/sources/browser/Potato.sol | Return amount of tokens that {account} gets during potato yields Used both internally and externally to calculate the potato yield amount account is an address of token holder to calculate for return amount of tokens that player could get/ The potato yield is not a part of total supply, since it was moved out of balances potato yield owed proportional to current balance of the account. The decimal factor is used to avoid floating issue. | function potatoYieldOwing (address account) public view returns(uint256) {
Account memory _account = _accounts[account];
uint256 newpotatoYield = totalPotatoYield.sub(_account.lastPotatoYield);
uint256 proportion = _account.balance.mul(newpotatoYield);
uint256 supply = _totalSupply.sub(newpotatoYield);
uint256 potatoYield = proportion.mul(_decimalFactor).div(supply).div(_decimalFactor);
return potatoYield;
}
| 13,366,777 |
./full_match/5/0x58a44849E4bA7B5273ad8D790ff92aa57BE305D7/sources/contracts/CrowdFunding.sol | create an array of allCampaignsloop and populate campign var above | function getCampaigns() public view returns (Campaign[] memory){
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for(uint i = 0; i < numberOfCampaigns; i++){
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
return allCampaigns;
}
| 1,918,599 |
./partial_match/1/0x3656c1a7f1c05900f03E279358C7141617d4473a/sources/BULLKING.sol | / Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol SPDX-License-Identifier: MIT pragma solidity ^0.8.0; Interface of the ERC20 standard as defined in the EIP./ | interface BEP20 {
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);
BULLKING
}
| 9,320,260 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract InkersHKCollection is ERC1155, Ownable, Pausable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping(uint256 => address payable) originalOwners;
mapping(uint256 => bool) public orderedOriginalPrints;
mapping(uint256 => address payable[]) copiesOwner;
mapping(uint256 => uint256) copyCountForOriginal;
uint earlyAccessOriginalsCount = 40;
uint256 firstOriginalPrice = 0.1 ether;
uint256 firstCopyPrice = 0.05 ether;
uint maximumMintableOriginals = 100;
uint copyNumberPriceFactor = 150;
uint originalNumberPriceFactor = 110;
constructor() public ERC1155("https://nft.inkers.app/api/metadatas/{id}-metadatas.json") {
}
// 8888888b. d8888 Y88b d88P d8888 888888b. 888 8888888888 .d8888b.
// 888 Y88b d88888 Y88b d88P d88888 888 "88b 888 888 d88P Y88b
// 888 888 d88P888 Y88o88P d88P888 888 .88P 888 888 Y88b.
// 888 d88P d88P 888 Y888P d88P 888 8888888K. 888 8888888 "Y888b.
// 8888888P" d88P 888 888 d88P 888 888 "Y88b 888 888 "Y88b.
// 888 d88P 888 888 d88P 888 888 888 888 888 "888
// 888 d8888888888 888 d8888888888 888 d88P 888 888 Y88b d88P
// 888 d88P 888 888 d88P 888 8888888P" 88888888 8888888888 "Y8888P"
function generateNewOriginal() payable public whenNotPaused returns (uint256) {
uint256 nextOriginalPrice = this.getNextOriginalPrice();
require(
msg.value == nextOriginalPrice,
append("Must pay enought to mint a new original: ", uint2str(nextOriginalPrice))
);
require(
_tokenIds.current() / 3 < maximumMintableOriginals,
"No more original available"
);
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
// reserve the next two slots for copies and printed copies
_tokenIds.increment();
_tokenIds.increment();
_mint(msg.sender, newTokenId, 1, "");
originalOwners[newTokenId] = msg.sender;
emit OriginalCreated(msg.sender, newTokenId);
return newTokenId;
}
function generateNewCopy(uint256 id) payable public whenNotPaused returns (uint256) {
require(isOriginal(id), "Can only copy originals");
uint256 nextCopyPrice = this.getCopyPrice(id);
require(
msg.value == nextCopyPrice,
append("Must pay at least nextCopyPrice to mint a new copy: ", uint2str(nextCopyPrice))
);
uint256 copiesId = id+1;
// pay commission
uint256 originalOwnerCommission = msg.value.mul(30).div(100);
address owner = originalOwners[id];
(bool success, ) = owner.call{value: originalOwnerCommission}("");
require(success, "Payment to owner failed");
// if a copies owner exist, we have to pay their commissions too
if (copiesOwner[copiesId].length > 0) {
uint256 copiesOwnersCommission = msg.value.mul(30).div(100).div(copiesOwner[copiesId].length);
for (uint256 i = 0; i < copiesOwner[copiesId].length; i++) {
address copyOwner = copiesOwner[copiesId][i];
(bool copyOwnerSuccess, ) = copyOwner.call{value: copiesOwnersCommission}("");
require(copyOwnerSuccess, "Payment to copy owner failed");
}
}
copyCountForOriginal[id]++;
_mint(msg.sender, copiesId, 1, "");
copiesOwner[copiesId].push(msg.sender);
emit CopyCreated(msg.sender, id);
return copiesId;
}
function orderPrint(uint256 id) whenNotPaused public {
require(
!isPrintedCopy(id),
"Cannot print an already printed copy"
);
// if it's a copy, we'll have to change it to a printed copy
// so it cannot be printed twice
if (isCopy(id)) {
require(
balanceOf(msg.sender, id) > 0,
append("Must own an unprinted copy for this id: ", uint2str(id))
);
// exchange a copy with a printed copy
_mint(msg.sender, id+1, 1, "");
_burn(msg.sender, id, 1);
} else if (isOriginal(id)) {
require(
balanceOf(msg.sender, id) > 0,
append("Must own an unprinted original for this id: ", uint2str(id))
);
require(
orderedOriginalPrints[id] != true,
"This print has already been ordered"
);
orderedOriginalPrints[id] = true;
}
emit PrintOrdered(msg.sender, id);
}
// 8888888b. 888 888 8888888b. 8888888888 .d8888b.
// 888 Y88b 888 888 888 Y88b 888 d88P Y88b
// 888 888 888 888 888 888 888 Y88b.
// 888 d88P 888 888 888 d88P 8888888 "Y888b.
// 8888888P" 888 888 8888888P" 888 "Y88b.
// 888 888 888 888 T88b 888 "888
// 888 Y88b. .d88P 888 T88b 888 Y88b d88P
// 888 "Y88888P" 888 T88b 8888888888 "Y8888P"
function append(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function isOriginal(uint id) public pure returns (bool) {
return id % 3 == 1;
}
function isCopy(uint id) public pure returns (bool) {
return id % 3 == 2;
}
function isPrintedCopy(uint id) public pure returns (bool) {
return id % 3 == 0;
}
// 888 888 8888888 8888888888 888 888 .d8888b.
// 888 888 888 888 888 o 888 d88P Y88b
// 888 888 888 888 888 d8b 888 Y88b.
// Y88b d88P 888 8888888 888 d888b 888 "Y888b.
// Y88b d88P 888 888 888d88888b888 "Y88b.
// Y88o88P 888 888 88888P Y88888 "888
// Y888P 888 888 8888P Y8888 Y88b d88P
// Y8P 8888888 8888888888 888P Y888 "Y8888P"
function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) {
uint256 index;
// first count all tokens
uint256 tokenCount=0;
for (index = 0; index < _tokenIds.current(); index++) {
tokenCount += balanceOf(_owner, index+1);
}
// then iterate over all tokens to find the ones owned
// by the requested owners
uint256[] memory result = new uint256[](tokenCount);
uint256 insertingIndex = 0;
for (index = 0; index < _tokenIds.current(); index++) {
uint balance = balanceOf(_owner, index+1);
uint256 index2;
for (index2 = 0; index2 < balance; index2++) {
result[insertingIndex++] = index+1;
}
}
return result;
}
function getCopyPrice(uint256 id) external view returns (uint256) {
uint256 nextCopyCount = copyCountForOriginal[id];
uint index;
uint256 nextCopyPrice = firstCopyPrice;
for (index = 0; index < nextCopyCount; index++) {
nextCopyPrice = nextCopyPrice * copyNumberPriceFactor / 100;
}
return nextCopyPrice;
}
function getNextOriginalPrice() external view returns (uint256) {
uint256 currentToken = _tokenIds.current()/3;
if (currentToken <= earlyAccessOriginalsCount) {
currentToken = 0;
} else {
currentToken -= earlyAccessOriginalsCount;
}
uint256 current = currentToken/5;
uint index;
uint256 nextOriginalPrice = firstOriginalPrice;
for (index = 0; index < current; index++) {
nextOriginalPrice = nextOriginalPrice * originalNumberPriceFactor / 100;
}
return nextOriginalPrice;
}
function getCopyCount(uint256 id) external view returns (uint256) {
return copyCountForOriginal[id];
}
function getCopyOwners(uint256 id) external view returns (address payable[] memory) {
return copiesOwner[id];
}
// 888 888 .d88888b. .d88888b. 888 d8P .d8888b.
// 888 888 d88P" "Y88b d88P" "Y88b 888 d8P d88P Y88b
// 888 888 888 888 888 888 888 d8P Y88b.
// 8888888888 888 888 888 888 888d88K "Y888b.
// 888 888 888 888 888 888 8888888b "Y88b.
// 888 888 888 888 888 888 888 Y88b "888
// 888 888 Y88b. .d88P Y88b. .d88P 888 Y88b Y88b d88P
// 888 888 "Y88888P" "Y88888P" 888 Y88b "Y8888P"
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);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
// transfer originals
if (originalOwners[id] == from) {
originalOwners[id] = payable(to);
}
// transfer copies and printed copies
if (id % 3 == 0) {
id--; // use copiesId for printedCopiesId
}
for (uint j = 0; j < copiesOwner[id].length; j++) {
if (copiesOwner[id][j] == from &&
to != address(0x0) /* ignore burning of copies for printed copies */) {
copiesOwner[id][j] = payable(to);
}
}
}
}
//
// d8888 8888888b. 888b d888 8888888 888b 888
// d88888 888 "Y88b 8888b d8888 888 8888b 888
// d88P888 888 888 88888b.d88888 888 88888b 888
// d88P 888 888 888 888Y88888P888 888 888Y88b 888
// d88P 888 888 888 888 Y888P 888 888 888 Y88b888
// d88P 888 888 888 888 Y8P 888 888 888 Y88888
// d8888888888 888 .d88P 888 " 888 888 888 Y8888
// d88P 888 8888888P" 888 888 8888888 888 Y888
function cancelPrintRequest(address requester, uint256 tokenId) public onlyOwner {
require(
isPrintedCopy(tokenId) ||
(isOriginal(tokenId) && orderedOriginalPrints[tokenId] == true),
"TokenID must be a printed copy or a printed original"
);
require(
balanceOf(requester, tokenId) > 0,
"Requester must own at leasts one token of requested type"
);
if (isPrintedCopy(tokenId)) {
_mint(requester, tokenId-1, 1, "");
_burn(requester, tokenId, 1);
} else if (isOriginal(tokenId)) {
orderedOriginalPrints[tokenId] = false;
}
}
function changeFirstOriginalPrice(uint256 newPrice) public onlyOwner {
firstOriginalPrice = newPrice;
}
function changeCopyNumberPriceFactor(uint256 newFactor) public onlyOwner {
copyNumberPriceFactor = newFactor;
}
function changeOriginalNumberPriceFactor(uint256 newFactor) public onlyOwner {
originalNumberPriceFactor = newFactor;
}
function changeFirstCopyPrice(uint256 newPrice) public onlyOwner {
firstCopyPrice = newPrice;
}
function changeMaximumMintableOriginals(uint256 newMaximum) public onlyOwner {
maximumMintableOriginals = newMaximum;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function setURI(string memory newuri) internal virtual onlyOwner {
_setURI(newuri);
}
function withdraw() public onlyOwner {
uint256 withdrawableFunds = address(this).balance;
msg.sender.transfer(withdrawableFunds);
}
// 8888888888 888 888 8888888888 888b 888 88888888888 .d8888b.
// 888 888 888 888 8888b 888 888 d88P Y88b
// 888 888 888 888 88888b 888 888 Y88b.
// 8888888 Y88b d88P 8888888 888Y88b 888 888 "Y888b.
// 888 Y88b d88P 888 888 Y88b888 888 "Y88b.
// 888 Y88o88P 888 888 Y88888 888 "888
// 888 Y888P 888 888 Y8888 888 Y88b d88P
// 8888888888 Y8P 8888888888 888 Y888 888 "Y8888P"
event OriginalCreated(address indexed to, uint256 id);
event PrintOrdered(address indexed to, uint256 id);
event CopyCreated(address indexed to, uint256 originalId);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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.0 <0.8.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../utils/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address 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;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @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) external 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 {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(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 `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 {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, 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 (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
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 `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @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 IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).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 IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.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 IERC1155MetadataURI is IERC1155 {
/**
* @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
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@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
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
| reserve the next two slots for copies and printed copies | function generateNewOriginal() payable public whenNotPaused returns (uint256) {
uint256 nextOriginalPrice = this.getNextOriginalPrice();
require(
msg.value == nextOriginalPrice,
append("Must pay enought to mint a new original: ", uint2str(nextOriginalPrice))
);
require(
_tokenIds.current() / 3 < maximumMintableOriginals,
"No more original available"
);
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
_tokenIds.increment();
_tokenIds.increment();
_mint(msg.sender, newTokenId, 1, "");
originalOwners[newTokenId] = msg.sender;
emit OriginalCreated(msg.sender, newTokenId);
return newTokenId;
}
| 12,052,247 |
./full_match/3/0xc9Ee84d508b6d038a9f66b29b86cfe1F4DE1ae39/sources/contracts/Alloy.sol | Mint a token redeemable only by a user who own the specified array of token Ids. | function mintAlloy(uint256[] memory ids, string memory URI)
public
onlyOwner
returns (uint256)
{
_tokenIds.increment();
uint256 newId = _tokenIds.current();
_safeMint(msg.sender, newId);
_setTokenURI(newId, URI);
_setRequirements(newId, ids);
return newId;
}
| 8,160,550 |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/Pool.sol | Get redemption account Account tick Tick redemptionId Redemption ID return Redemption/ | function redemptions(
address account,
uint128 tick,
uint128 redemptionId
) external view returns (Redemption memory) {
return _deposits[account][tick].redemptions[redemptionId];
}
| 9,659,154 |
/**
*Submitted for verification at Etherscan.io on 2022-01-30
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.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
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
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;
}
}
/**
* ERC20 standard interface.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev 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;
}
/**
* @dev Returns the minimum value among two unsigned integers. (unsigned integer modulo)
*/
function min(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a < b ? a : b;
}
/**
* @dev Returns the maximum value among two unsigned integers. (unsigned integer modulo)
*/
function max(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a > b ? a : b;
}
}
contract SafeToken is Ownable {
address payable _safeManager;
constructor() {
_safeManager = payable(_msgSender());
}
function setSafeManager(address payable account) public onlyOwner {
_safeManager = account;
}
function withdraw(address contractAddress, uint256 amount) external {
require(_msgSender() == _safeManager, "SafeToken: caller is not the owner");
IERC20(contractAddress).transfer(_safeManager, amount);
}
function withdrawETH(uint256 amount) external {
require(_msgSender() == _safeManager, "SafeToken: caller is not the owner");
_safeManager.transfer(amount);
}
}
contract LockToken is Ownable {
mapping(address => bool) private _blackList;
modifier open(address account) {
require(!_blackList[account], "LockToken: caller is blacklisted");
_;
}
function includeToBlackList(address account) external onlyOwner {
_blackList[account] = true;
}
function excludeFromBlackList(address account) external onlyOwner {
_blackList[account] = false;
}
}
contract CLAW is Ownable, IERC20, IERC20Metadata, SafeToken, LockToken {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) _allowances;
string private _name = "CryptoClaw";
string private _symbol = "CLAW";
uint8 private _decimals = 9;
uint256 private _totalSupply = 10000000 * (10 ** _decimals);
constructor() {
_balances[address(this)] = _totalSupply;
emit Transfer(address(0), address(this), _totalSupply);
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() external view override returns (string memory) {
return _name;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view override returns (uint8) {
return _decimals;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(amount));
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 {ERC20-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 amount) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(amount, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
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 open(sender) {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "ERC20: transfer amount is zero");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
require(amount > 0, "ERC20: approve amount is zero");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, 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 Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
// Function to receive Ether. msg.data must be empty
receive() external payable {}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
event Bought(uint256 amount);
mapping(uint8 => uint256) _tokenOptionAmounts;
mapping(uint8 => uint256) _ethOptionAmounts;
function getBuyOption(uint8 option) external view returns (uint256 ethAmount, uint256 tokenAmount) {
ethAmount = _ethOptionAmounts[option];
tokenAmount = _tokenOptionAmounts[option];
}
function setBuyOption(uint8 option, uint256 tokenAmount, uint256 ethAmount) external onlyOwner {
_tokenOptionAmounts[option] = tokenAmount;
_ethOptionAmounts[option] = ethAmount;
}
function buy(uint8 option) public payable {
require(_tokenOptionAmounts[option] > 0 && _ethOptionAmounts[option] > 0, "DEX: option is invalid");
require(msg.value == _ethOptionAmounts[option], "DEX: transfer amount is invalid");
// Call returns a boolean value indicating success or failure.
(bool sent, ) = payable(owner()).call{value: msg.value}("");
require(sent, "DEX: failed to send Ether");
// Transfer token to caller(buyer)
_transfer(address(this), _msgSender(), _tokenOptionAmounts[option]);
emit Bought(_tokenOptionAmounts[option]);
}
event JoinGame(address indexed account);
uint256 public gameCost;
function setGameCost(uint256 value) external onlyOwner returns (bool) {
require(value > 0, "Game: game cost is zero");
gameCost = value;
return true;
}
function joinGame() external returns (bool) {
_transfer(_msgSender(), address(this), gameCost);
emit JoinGame(_msgSender());
return true;
}
} | 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 {ERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./ | function increaseAllowance(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(amount));
return true;
}
| 10,692,411 |
pragma solidity ^0.5.0;
import "./StarToken.sol";
import "./DaiToken.sol";
contract TokenFarm {
//All code goes here...
string public name = "Star Token Farm";
StarToken public starToken;
DaiToken public daiToken;
address owner;
address[] public stakers;
mapping(address => uint) public stakingBalance;
mapping(address => bool) public hasStaked;
mapping(address => bool) public isStaking;
constructor(StarToken _starToken, DaiToken _daiToken) public {
starToken = _starToken;
daiToken = _daiToken;
owner = msg.sender;
}
// 1. Stake Tokens (Deposits)
function stakeTokens(uint _amount) public {
// Require amount greater than 0
require(_amount >0, "amount cannot be 0");
// Transfer Mock Dai tokens to this contract for staking
daiToken.transferFrom(msg.sender, address(this), _amount);
// Update staking balance
stakingBalance[msg.sender] += _amount;
// Add user to stakers array *only* if they haven't staked already
if(!hasStaked[msg.sender]){
stakers.push(msg.sender);
}
// Update staking status
isStaking[msg.sender] = true;
hasStaked[msg.sender] = true;
}
// 2. Unstaking Tokens (Withdraw)
function unstakeTokens() public{
// Fetch staking balance
uint balance = stakingBalance[msg.sender];
// Require amoount greater than 0
require(balance > 0, "The staking balance cannot be 0");
// Transfer Mock Dai tokens to this contract for staking
daiToken.transfer(msg.sender, balance);
// Reset staking balance
stakingBalance[msg.sender] = 0;
// Update Staking Status
isStaking[msg.sender] = false;
}
// 3. Issuing Tokens
function issueToken() public {
// Only owner can call this function
require(msg.sender == owner, "The caller must be owner");
// Issue tokens to all stakers
for(uint i=0; i <stakers.length; i++){
address recipient = stakers[i];
uint balance = stakingBalance[recipient];
if(balance >0){
starToken.transfer(recipient, balance);
}
}
}
}
| Require amount greater than 0 Transfer Mock Dai tokens to this contract for staking Update staking balance Add user to stakers array only if they haven't staked already | function stakeTokens(uint _amount) public {
require(_amount >0, "amount cannot be 0");
daiToken.transferFrom(msg.sender, address(this), _amount);
stakingBalance[msg.sender] += _amount;
if(!hasStaked[msg.sender]){
stakers.push(msg.sender);
}
hasStaked[msg.sender] = true;
}
| 12,710,580 |
./full_match/44787/0x7DE829829E8cC51dDD8e15D77DbC3f406fFA1bcC/sources/_aave/core-v3/contracts/interfaces/ICreditDelegationToken.sol | ICreditDelegationToken Aave Defines the basic interface for a token supporting credit delegation./ | interface ICreditDelegationToken {
event BorrowAllowanceDelegated(
address indexed fromUser,
address indexed toUser,
address indexed asset,
uint256 amount
);
function approveDelegation(address delegatee, uint256 amount) external;
function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
function delegationWithSig(
address delegator,
address delegatee,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
pragma solidity 0.8.14;
}
| 13,274,813 |
./full_match/1/0xcE9b49b0d4FE456aD6E4a1b7e4bBdD0699400Ef9/sources/src/vaults/borrowing/BorrowingVaultUpgradeable.sol | @inheritdoc IVaultUpgradeable | function previewMintDebt(uint256 shares) public view override returns (uint256 debt) {
return _convertToDebt(shares, Math.Rounding.Down);
}
| 2,939,920 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "./IERC2981.sol";
contract BlankArt is ERC721, EIP712, ERC721URIStorage, Ownable, IERC2981 {
event Initialized(
address controller,
address signer,
string baseURI,
uint256 mintPrice,
uint256 maxTokenSupply,
bool active,
bool publicMint
);
// An event whenever the foundation address is updated
event FoundationAddressUpdated(address foundationAddress);
// An event whenever the voucher signer address is updated
event VoucherSignersUpdated(address foundationAddress, bool active);
event BaseTokenUriUpdated(string baseTokenURI);
event PermanentURI(string _value, uint256 indexed _id); // https://docs.opensea.io/docs/metadata-standards
event Minted(uint256 tokenId, address member, string tokenURI);
event BlankRoyaltySet(address recipient, uint16 bps);
// if a token's URI has been locked or not
mapping(uint256 => uint256) public tokenURILocked;
// signing domain
string private constant SIGNING_DOMAIN = "BlankNFT";
// signature version
string private constant SIGNATURE_VERSION = "1";
// address which signs the voucher
mapping(address => bool) _voucherSigners;
// Array of _baseURIs
string[] private _baseURIs;
// gets incremented to placehold for tokens not minted yet
uint256 public maxTokenSupply;
// cost to mint during the public sale
uint256 public mintPrice;
// Enables/Disables voucher redemption
bool public active;
// Enables/Disables public minting (without a whitelisted voucher)
bool public publicMint;
// the address of the platform (for receiving commissions and royalties)
address payable public foundationAddress;
// pending withdrawals by account address
mapping(address => uint256) pendingWithdrawals;
// Max number of tokens a member can mint
uint8 public memberMaxMintCount;
// current token index
uint256 public tokenIndex;
// pending withdrawals by account address
mapping(bytes32 => bool) private voucherClaimed;
// EIP2981
struct RoyaltyInfo {
address recipient;
uint24 bps;
}
RoyaltyInfo public blankRoyalty;
constructor(
address payable _foundationAddress,
address _signer,
uint256 _maxTokenSupply,
string memory baseURI,
uint16 _royaltyBPS
) ERC721("BlankArt", "BLANK") EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {
memberMaxMintCount = 5;
foundationAddress = _foundationAddress;
_voucherSigners[_signer] = true;
maxTokenSupply = _maxTokenSupply;
require(maxTokenSupply > 0);
tokenIndex = 1;
mintPrice = 0;
publicMint = false;
_baseURIs.push("");
// Default the initial index to 1. The lockTokenURI map will default to 0 for all unmapped tokens.
_baseURIs.push(baseURI);
active = true;
emit Initialized(
foundationAddress,
_signer,
baseURI,
mintPrice,
maxTokenSupply,
active,
publicMint
);
//Setup the initial royalty recipient and amount
blankRoyalty = RoyaltyInfo(_foundationAddress, _royaltyBPS);
}
/// @notice Represents a voucher to claim any un-minted NFT (up to memberMaxMintCount), which has not yet been recorded into the blockchain. A signed voucher can be redeemed for real NFTs using the redeemVoucher function.
struct BlankNFTVoucher {
/// @notice address of intended redeemer
address redeemerAddress;
/// @notice Expiration of the voucher, expressed in seconds since the Unix epoch.
uint256 expiration;
/// @notice The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT.
uint256 minPrice;
/// @notice amount of tokens the voucher can claim.
uint16 tokenCount;
/// @notice the EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE.
bytes signature;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function isMember(address account) external view returns (bool) {
return (balanceOf(account) > 0);
}
function addBaseURI(string calldata baseURI) external onlyOwner {
_baseURIs.push(baseURI);
emit BaseTokenUriUpdated(baseURI);
}
// Overridden. Gets the TokenURI based on the locked version.
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
string memory _base = "";
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
if (tokenURILocked[tokenId] > 0) _base = _baseURIs[tokenURILocked[tokenId]];
else _base = _baseURIs[_baseURIs.length - 1];
return string(abi.encodePacked(_base, Strings.toString(tokenId), ".json"));
}
function _checkMemberMintCount(address account) internal view {
if (balanceOf(account) >= memberMaxMintCount) {
revert(
string(
abi.encodePacked(
"Account ",
Strings.toHexString(uint160(account), 20),
" has reached its minting limit of ",
memberMaxMintCount,
", so cannot mint"
)
)
);
}
}
// Allows the current foundation address to update to something different
function updateFoundationAddress(address payable newFoundationAddress) external onlyOwner {
foundationAddress = newFoundationAddress;
emit FoundationAddressUpdated(newFoundationAddress);
}
// Allows the voucher signing address
function addVoucherSigner(address newVoucherSigner) external onlyOwner {
_voucherSigners[newVoucherSigner] = true;
emit VoucherSignersUpdated(newVoucherSigner, true);
}
// Disallows a voucher signing address
function removeVoucherSigner(address oldVoucherSigner) external onlyOwner {
_voucherSigners[oldVoucherSigner] = false;
emit VoucherSignersUpdated(oldVoucherSigner, false);
}
// Locks a token's URI from being updated. Only callable by the token owner.
function lockTokenURI(uint256 tokenId) external {
// ensure that this token exists
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
// ensure that the token is owned by the caller
require(ownerOf(tokenId) == msg.sender, "Invalid: Only the owner can lock their token");
// lock this token's URI from being changed
tokenURILocked[tokenId] = _baseURIs.length - 1;
emit PermanentURI(tokenURI(tokenId), tokenId);
}
// Updates the mintPrice
function updateMintPrice(uint256 price) external onlyOwner {
// Update the mintPrice
mintPrice = price;
}
// Updates the memberMaxMintCount
function updateMaxMintCount(uint8 _maxMint) external onlyOwner {
require(_maxMint > 0, "Max mint cannot be zero");
memberMaxMintCount = _maxMint;
}
// Toggle the value of publicMint
function togglePublicMint() external onlyOwner {
publicMint = !publicMint;
}
// Pause minting
function toggleActivation() external onlyOwner {
active = !active;
}
function _mintBlank(address owner) private returns (uint256) {
uint256 tokenId = tokenIndex;
_checkMemberMintCount(owner);
super._safeMint(owner, tokenId);
tokenIndex++;
string memory tokenUri = tokenURI(tokenId);
emit Minted(tokenId, owner, tokenUri);
return tokenId;
}
function redeemVoucher(uint256 amount, BlankNFTVoucher calldata voucher)
public
payable
returns (uint256[] memory)
{
// make sure voucher redemption period is active
require(active, "Voucher redemption is not currently active");
// make sure signature is valid and get the address of the signer
address signer = _verify(voucher);
// make sure caller is the redeemer
require(msg.sender == voucher.redeemerAddress, "Voucher is for a different wallet address");
// make sure voucher has not expired.
require(block.timestamp <= voucher.expiration, "Voucher has expired");
// make sure that the signer is the designated signer
require(_voucherSigners[signer], "Signature invalid or unauthorized");
require(
balanceOf(voucher.redeemerAddress) + amount <= memberMaxMintCount,
"Amount is more than the minting limit"
);
require(tokenIndex + amount <= maxTokenSupply + 1, "All tokens have already been minted");
// make sure that the redeemer is paying enough to cover the buyer's cost
require(msg.value >= (voucher.minPrice * amount), "Insufficient funds to redeem");
require(amount <= voucher.tokenCount, "Amount is more than the voucher allows");
// make sure voucher has not already been claimed. If true, it HAS been claimed
require(!voucherClaimed[_hash(voucher)], "Voucher has already been claimed");
// assign the token directly to the redeemer
uint256[] memory tokenIds = new uint256[](amount);
for (uint256 num = 0; num < amount; num++) {
uint256 tokenId = _mintBlank(voucher.redeemerAddress);
tokenIds[num] = tokenId;
}
// record payment to signer's withdrawal balance
pendingWithdrawals[foundationAddress] += msg.value;
voucherClaimed[_hash(voucher)] = true;
return tokenIds;
}
// Public mint function. Whitelisted members will utilize redeemVoucher()
function mint(uint256 amount) public payable returns (uint256[] memory) {
require(publicMint && active, "Public minting is not active.");
require(
balanceOf(msg.sender) + amount <= memberMaxMintCount,
"Amount is more than the minting limit"
);
require(tokenIndex + amount <= maxTokenSupply + 1, "All tokens have already been minted");
// make sure that the caller is paying enough to cover the mintPrice
require(msg.value >= (mintPrice * amount), "Insufficient funds to mint");
// assign the token directly to the redeemer
uint256[] memory tokenIds = new uint256[](amount);
for (uint256 num = 0; num < amount; num++) {
uint256 tokenId = _mintBlank(msg.sender);
tokenIds[num] = tokenId;
}
// record payment to foundationAddress withdrawal balance
pendingWithdrawals[foundationAddress] += msg.value;
return tokenIds;
}
/// @notice Transfers all pending withdrawal balance to the caller. Reverts if the caller is not an authorized minter.
function withdraw() public {
// IMPORTANT: casting msg.sender to a payable address is only safe if ALL members of the minter role are payable addresses.
address payable receiver = payable(msg.sender);
uint256 amount = pendingWithdrawals[receiver];
// zero account before transfer to prevent re-entrancy attack
pendingWithdrawals[receiver] = 0;
receiver.transfer(amount);
}
/// @notice Returns the amount of Ether available to the caller to withdraw.
function availableToWithdraw() public view returns (uint256) {
return pendingWithdrawals[msg.sender];
}
/// @notice Returns a hash of the given BlankNFTVoucher, prepared using EIP712 typed data hashing rules.
/// @param voucher An NFTVoucher to hash.
function _hash(BlankNFTVoucher calldata voucher) internal view returns (bytes32) {
return
_hashTypedDataV4(
keccak256(
abi.encode(
keccak256(
"BlankNFTVoucher(address redeemerAddress,uint256 expiration,uint256 minPrice,uint16 tokenCount)"
),
voucher.redeemerAddress,
voucher.expiration,
voucher.minPrice,
voucher.tokenCount
)
)
);
}
/// @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;
}
/// @notice Verifies the signature for a given BlankNFTVoucher, returning the address of the signer.
/// @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs.
/// @param voucher An BlankNFTVoucher describing an unminted NFT.
function _verify(BlankNFTVoucher calldata voucher) internal view returns (address) {
bytes32 digest = _hash(voucher);
return ECDSA.recover(digest, voucher.signature);
}
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param - the tokenId queried for royalty information --Not Utilized, All tokens have the same royalty
/// @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, uint256 salePrice)
external
view
override(IERC2981)
returns (address receiver, uint256 royaltyAmount)
{
return (
blankRoyalty.recipient,
(salePrice * blankRoyalty.bps) / 10000
);
}
/// @dev Update the address which receives royalties, and the fee charged
/// @param recipient address of who should be sent the royalty payment
/// @param bps uint256 amount of fee (1% == 100)
function setDefaultRoyalty(address recipient, uint16 bps)
public
onlyOwner
{
blankRoyalty = RoyaltyInfo(recipient, bps);
emit BlankRoyaltySet(recipient, bps);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, IERC165)
returns (bool)
{
return ERC721.supportsInterface(interfaceId) || interfaceId == type(IERC2981).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;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.4;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 is IERC165 {
/// 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
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);
} | make sure voucher redemption period is active make sure signature is valid and get the address of the signer make sure caller is the redeemer make sure voucher has not expired. make sure that the signer is the designated signer make sure that the redeemer is paying enough to cover the buyer's cost make sure voucher has not already been claimed. If true, it HAS been claimed assign the token directly to the redeemer | function redeemVoucher(uint256 amount, BlankNFTVoucher calldata voucher)
public
payable
returns (uint256[] memory)
{
require(active, "Voucher redemption is not currently active");
address signer = _verify(voucher);
require(msg.sender == voucher.redeemerAddress, "Voucher is for a different wallet address");
require(block.timestamp <= voucher.expiration, "Voucher has expired");
require(_voucherSigners[signer], "Signature invalid or unauthorized");
require(
balanceOf(voucher.redeemerAddress) + amount <= memberMaxMintCount,
"Amount is more than the minting limit"
);
require(tokenIndex + amount <= maxTokenSupply + 1, "All tokens have already been minted");
require(msg.value >= (voucher.minPrice * amount), "Insufficient funds to redeem");
require(amount <= voucher.tokenCount, "Amount is more than the voucher allows");
require(!voucherClaimed[_hash(voucher)], "Voucher has already been claimed");
uint256[] memory tokenIds = new uint256[](amount);
for (uint256 num = 0; num < amount; num++) {
uint256 tokenId = _mintBlank(voucher.redeemerAddress);
tokenIds[num] = tokenId;
}
voucherClaimed[_hash(voucher)] = true;
return tokenIds;
}
| 11,899,092 |
./full_match/4/0x8436267B8b0f3051641d4ec453307e94165991AB/sources/browser/1155-clone-factory.sol | Creates `amount` new tokens for `to`, of token type `id`. See {ERC1155-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./ | function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155License: must have minter role to mint");
_mint(to, id, amount, data);
}
| 807,670 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.0;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC4626Vault is IERC20 {
/// @notice The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing
function asset() external view returns (address assetTokenAddress);
/// @notice Total amount of the underlying asset that is “managed” by Vault
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.
* @param assets The amount of underlying assets to be convert to vault shares.
* @return shares The amount of vault shares converted from the underlying assets.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.
* @param shares The amount of vault shares to be converted to the underlying assets.
* @return assets The amount of underlying assets converted from the vault shares.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @notice The maximum number of underlying assets that caller can deposit.
* @param caller Account that the assets will be transferred from.
* @return maxAssets The maximum amount of underlying assets the caller can deposit.
*/
function maxDeposit(address caller) external view returns (uint256 maxAssets);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be transferred.
* @return shares The amount of vault shares that will be minted.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.
* @param assets The amount of underlying assets to be transferred to the vault.
* @param receiver The account that the vault shares will be minted to.
* @return shares The amount of vault shares that were minted.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @notice The maximum number of vault shares that caller can mint.
* @param caller Account that the underlying assets will be transferred from.
* @return maxShares The maximum amount of vault shares the caller can mint.
*/
function maxMint(address caller) external view returns (uint256 maxShares);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions.
* @param shares The amount of vault shares to be minted.
* @return assets The amount of underlying assests that will be transferred from the caller.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.
* @param shares The amount of vault shares to be minted.
* @param receiver The account the vault shares will be minted to.
* @return assets The amount of underlying assets that were transferred from the caller.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @notice The maximum number of underlying assets that owner can withdraw.
* @param owner Account that owns the vault shares.
* @return maxAssets The maximum amount of underlying assets the owner can withdraw.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be withdrawn.
* @return shares The amount of vault shares that will be burnt.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.
* @param assets The amount of underlying assets to be withdrawn from the vault.
* @param receiver The account that the underlying assets will be transferred to.
* @param owner Account that owns the vault shares to be burnt.
* @return shares The amount of vault shares that were burnt.
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice The maximum number of shares an owner can redeem for underlying assets.
* @param owner Account that owns the vault shares.
* @return maxShares The maximum amount of shares the owner can redeem.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions.
* @param shares The amount of vault shares to be burnt.
* @return assets The amount of underlying assests that will transferred to the receiver.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.
* @param shares The amount of vault shares to be burnt.
* @param receiver The account the underlying assets will be transferred to.
* @param owner The account that owns the vault shares to be burnt.
* @return assets The amount of underlying assets that were transferred to the receiver.
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/*///////////////////////////////////////////////////////////////
Events
//////////////////////////////////////////////////////////////*/
/**
* @dev Emitted when caller has exchanged assets for shares, and transferred those shares to owner.
*
* Note It must be emitted when tokens are deposited into the Vault in ERC4626.mint or ERC4626.deposit methods.
*
*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
/**
* @dev Emitted when sender has exchanged shares for assets, and transferred those assets to receiver.
*
* Note It must be emitted when shares are withdrawn from the Vault in ERC4626.redeem or ERC4626.withdraw methods.
*
*/
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
}
interface IUnwrapper {
// @dev Get bAssetOut status
function getIsBassetOut(
address _masset,
bool _inputIsCredit,
address _output
) external view returns (bool isBassetOut);
/// @dev Estimate output
function getUnwrapOutput(
bool _isBassetOut,
address _router,
address _input,
bool _inputIsCredit,
address _output,
uint256 _amount
) external view returns (uint256 output);
/// @dev Unwrap and send
function unwrapAndSend(
bool _isBassetOut,
address _router,
address _input,
address _output,
uint256 _amount,
uint256 _minAmountOut,
address _beneficiary
) external returns (uint256 outputQuantity);
}
interface ISavingsManager {
/** @dev Admin privs */
function distributeUnallocatedInterest(address _mAsset) external;
/** @dev Liquidator */
function depositLiquidation(address _mAsset, uint256 _liquidation) external;
/** @dev Liquidator */
function collectAndStreamInterest(address _mAsset) external;
/** @dev Public privs */
function collectAndDistributeInterest(address _mAsset) external;
}
interface ISavingsContractV4 is IERC4626Vault {
// DEPRECATED but still backwards compatible
function redeem(uint256 _amount) external returns (uint256 massetReturned);
function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf)
// --------------------------------------------
function depositInterest(uint256 _amount) external; // V1 & V2
function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2
function depositSavings(uint256 _amount, address _beneficiary)
external
returns (uint256 creditsIssued); // V2
function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2
function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2
function exchangeRate() external view returns (uint256); // V1 & V2
function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2
function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2
function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2
// --------------------------------------------
function redeemAndUnwrap(
uint256 _amount,
bool _isCreditAmt,
uint256 _minAmountOut,
address _output,
address _beneficiary,
address _router,
bool _isBassetOut
)
external
returns (
uint256 creditsBurned,
uint256 massetRedeemed,
uint256 outputQuantity
);
function depositSavings(
uint256 _underlying,
address _beneficiary,
address _referrer
) external returns (uint256 creditsIssued);
function deposit(
uint256 assets,
address receiver,
address referrer
) external returns (uint256 shares);
function mint(
uint256 shares,
address receiver,
address referrer
) external returns (uint256 assets);
}
/*
* @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 {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
// constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract ERC205 is Context, IERC20 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view 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 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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - 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(_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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - 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] -= 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 {
require(account != address(0), "ERC20: mint to the zero address");
_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 {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()] - amount);
}
}
abstract contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
abstract contract InitializableToken is ERC205, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg) internal {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
interface IConnector {
/**
* @notice Deposits the mAsset into the connector
* @param _amount Units of mAsset to receive and deposit
*/
function deposit(uint256 _amount) external;
/**
* @notice Withdraws a specific amount of mAsset from the connector
* @param _amount Units of mAsset to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @notice Withdraws all mAsset from the connector
*/
function withdrawAll() external;
/**
* @notice Returns the available balance in the connector. In connections
* where there is likely to be an initial dip in value due to conservative
* exchange rates (e.g. with Curves `get_virtual_price`), it should return
* max(deposited, balance) to avoid temporary negative yield. Any negative yield
* should be corrected during a withdrawal or over time.
* @return Balance of mAsset in the connector
*/
function checkBalance() external view returns (uint256);
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e38 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
/**
* @title SavingsContract
* @author mStable
* @notice Savings contract uses the ever increasing "exchangeRate" to increase
* the value of the Savers "credits" (ERC20) relative to the amount of additional
* underlying collateral that has been deposited into this contract ("interest")
* @dev VERSION: 2.2
* DATE: 2022-04-08
*/
contract SavingsContract_imbtc_mainnet_22 is
ISavingsContractV4,
Initializable,
InitializableToken,
ImmutableModule
{
using StableMath for uint256;
// Core events for depositing and withdrawing
event ExchangeRateUpdated(uint256 newExchangeRate, uint256 interestCollected);
event SavingsDeposited(address indexed saver, uint256 savingsDeposited, uint256 creditsIssued);
event CreditsRedeemed(
address indexed redeemer,
uint256 creditsRedeemed,
uint256 savingsCredited
);
event AutomaticInterestCollectionSwitched(bool automationEnabled);
// Connector poking
event PokerUpdated(address poker);
event FractionUpdated(uint256 fraction);
event ConnectorUpdated(address connector);
event EmergencyUpdate();
event Poked(uint256 oldBalance, uint256 newBalance, uint256 interestDetected);
event PokedRaw();
// Tracking events
event Referral(address indexed referrer, address beneficiary, uint256 amount);
// Rate between 'savings credits' and underlying
// e.g. 1 credit (1e17) mulTruncate(exchangeRate) = underlying, starts at 10:1
// exchangeRate increases over time
uint256 private constant startingRate = 1e17;
uint256 public override exchangeRate;
// Underlying asset is underlying
IERC20 public immutable underlying;
bool private automateInterestCollection;
// Yield
// Poker is responsible for depositing/withdrawing from connector
address public poker;
// Last time a poke was made
uint256 public lastPoke;
// Last known balance of the connector
uint256 public lastBalance;
// Fraction of capital assigned to the connector (100% = 1e18)
uint256 public fraction;
// Address of the current connector (all IConnectors are mStable validated)
IConnector public connector;
// How often do we allow pokes
uint256 private constant POKE_CADENCE = 4 hours;
// Max APY generated on the capital in the connector
uint256 private constant MAX_APY = 4e18;
uint256 private constant SECONDS_IN_YEAR = 365 days;
// Proxy contract for easy redemption
address public immutable unwrapper;
constructor(
address _nexus,
address _underlying,
address _unwrapper
) ImmutableModule(_nexus) {
require(_underlying != address(0), "mAsset address is zero");
require(_unwrapper != address(0), "Unwrapper address is zero");
underlying = IERC20(_underlying);
unwrapper = _unwrapper;
}
// Add these constants to bytecode at deploytime
function initialize(
address _poker,
string calldata _nameArg,
string calldata _symbolArg
) external initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
require(_poker != address(0), "Invalid poker address");
poker = _poker;
fraction = 2e17;
automateInterestCollection = true;
exchangeRate = startingRate;
}
/** @dev Only the savings managaer (pulled from Nexus) can execute this */
modifier onlySavingsManager() {
require(msg.sender == _savingsManager(), "Only savings manager can execute");
_;
}
/***************************************
VIEW - E
****************************************/
/**
* @dev Returns the underlying balance of a given user
* @param _user Address of the user to check
* @return balance Units of underlying owned by the user
*/
function balanceOfUnderlying(address _user) external view override returns (uint256 balance) {
(balance, ) = _creditsToUnderlying(balanceOf(_user));
}
/**
* @dev Converts a given underlying amount into credits
* @param _underlying Units of underlying
* @return credits Credit units (a.k.a imUSD)
*/
function underlyingToCredits(uint256 _underlying)
external
view
override
returns (uint256 credits)
{
(credits, ) = _underlyingToCredits(_underlying);
}
/**
* @dev Converts a given credit amount into underlying
* @param _credits Units of credits
* @return amount Corresponding underlying amount
*/
function creditsToUnderlying(uint256 _credits) external view override returns (uint256 amount) {
(amount, ) = _creditsToUnderlying(_credits);
}
// Deprecated in favour of `balanceOf(address)`
// Maintained for backwards compatibility
// Returns the credit balance of a given user
function creditBalances(address _user) external view override returns (uint256) {
return balanceOf(_user);
}
/***************************************
INTEREST
****************************************/
/**
* @dev Deposit interest (add to savings) and update exchange rate of contract.
* Exchange rate is calculated as the ratio between new savings q and credits:
* exchange rate = savings / credits
*
* @param _amount Units of underlying to add to the savings vault
*/
function depositInterest(uint256 _amount) external override onlySavingsManager {
require(_amount > 0, "Must deposit something");
// Transfer the interest from sender to here
require(underlying.transferFrom(msg.sender, address(this), _amount), "Must receive tokens");
// Calc new exchange rate, protect against initialisation case
uint256 totalCredits = totalSupply();
if (totalCredits > 0) {
// new exchange rate is relationship between _totalCredits & totalSavings
// _totalCredits * exchangeRate = totalSavings
// exchangeRate = totalSavings/_totalCredits
(uint256 totalCollat, ) = _creditsToUnderlying(totalCredits);
uint256 newExchangeRate = _calcExchangeRate(totalCollat + _amount, totalCredits);
exchangeRate = newExchangeRate;
emit ExchangeRateUpdated(newExchangeRate, _amount);
}
}
/** @dev Enable or disable the automation of fee collection during deposit process */
function automateInterestCollectionFlag(bool _enabled) external onlyGovernor {
automateInterestCollection = _enabled;
emit AutomaticInterestCollectionSwitched(_enabled);
}
/***************************************
DEPOSIT
****************************************/
/**
* @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected
* @param _underlying Units of underlying to deposit into savings vault
* @param _beneficiary Immediately transfer the imUSD token to this beneficiary address
* @return creditsIssued Units of credits (imUSD) issued
*/
function preDeposit(uint256 _underlying, address _beneficiary)
external
returns (uint256 creditsIssued)
{
require(exchangeRate == startingRate, "Can only use this method before streaming begins");
return _deposit(_underlying, _beneficiary, false);
}
/**
* @dev Deposit the senders savings to the vault, and credit them internally with "credits".
* Credit amount is calculated as a ratio of deposit amount and exchange rate:
* credits = underlying / exchangeRate
* We will first update the internal exchange rate by collecting any interest generated on the underlying.
* @param _underlying Units of underlying to deposit into savings vault
* @return creditsIssued Units of credits (imUSD) issued
*/
function depositSavings(uint256 _underlying) external override returns (uint256 creditsIssued) {
return _deposit(_underlying, msg.sender, true);
}
/**
* @dev Deposit the senders savings to the vault, and credit them internally with "credits".
* Credit amount is calculated as a ratio of deposit amount and exchange rate:
* credits = underlying / exchangeRate
* We will first update the internal exchange rate by collecting any interest generated on the underlying.
* @param _underlying Units of underlying to deposit into savings vault
* @param _beneficiary Immediately transfer the imUSD token to this beneficiary address
* @return creditsIssued Units of credits (imUSD) issued
*/
function depositSavings(uint256 _underlying, address _beneficiary)
external
override
returns (uint256 creditsIssued)
{
return _deposit(_underlying, _beneficiary, true);
}
/**
* @dev Overloaded `depositSavings` method with an optional referrer address.
* @param _underlying Units of underlying to deposit into savings vault
* @param _beneficiary Immediately transfer the imUSD token to this beneficiary address
* @param _referrer Referrer address for this deposit
* @return creditsIssued Units of credits (imUSD) issued
*/
function depositSavings(
uint256 _underlying,
address _beneficiary,
address _referrer
) external override returns (uint256 creditsIssued) {
emit Referral(_referrer, _beneficiary, _underlying);
return _deposit(_underlying, _beneficiary, true);
}
/**
* @dev Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD
*/
function _deposit(
uint256 _underlying,
address _beneficiary,
bool _collectInterest
) internal returns (uint256 creditsIssued) {
creditsIssued = _transferAndMint(_underlying, _beneficiary, _collectInterest);
}
/***************************************
REDEEM
****************************************/
// Deprecated in favour of redeemCredits
// Maintaining backwards compatibility, this fn minimics the old redeem fn, in which
// credits are redeemed but the interest from the underlying is not collected.
function redeem(uint256 _credits) external override returns (uint256 massetReturned) {
require(_credits > 0, "Must withdraw something");
(, uint256 payout) = _redeem(_credits, true, true);
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
return payout;
}
/**
* @dev Redeem specific number of the senders "credits" in exchange for underlying.
* Payout amount is calculated as a ratio of credits and exchange rate:
* payout = credits * exchangeRate
* @param _credits Amount of credits to redeem
* @return massetReturned Units of underlying mAsset paid out
*/
function redeemCredits(uint256 _credits) external override returns (uint256 massetReturned) {
require(_credits > 0, "Must withdraw something");
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
(, uint256 payout) = _redeem(_credits, true, true);
return payout;
}
/**
* @dev Redeem credits into a specific amount of underlying.
* Credits needed to burn is calculated using:
* credits = underlying / exchangeRate
* @param _underlying Amount of underlying to redeem
* @return creditsBurned Units of credits burned from sender
*/
function redeemUnderlying(uint256 _underlying)
external
override
returns (uint256 creditsBurned)
{
require(_underlying > 0, "Must withdraw something");
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
// Ensure that the payout was sufficient
(uint256 credits, uint256 massetReturned) = _redeem(_underlying, false, true);
require(massetReturned == _underlying, "Invalid output");
return credits;
}
/**
* @notice Redeem credits into a specific amount of underlying, unwrap
* into a selected output asset, and send to a beneficiary
* Credits needed to burn is calculated using:
* credits = underlying / exchangeRate
* @param _amount Units to redeem (either underlying or credit amount).
* @param _isCreditAmt `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD.
* @param _minAmountOut Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token.
* @param _output Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example:
- bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault.
- bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault.
- bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault.
* @param _beneficiary Address to send `output` tokens to.
* @param _router mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset.
* @param _isBassetOut `true` if `output` is a bAsset. `false` if `output` is a fAsset.
* @return creditsBurned Units of credits burned from sender. eg imUSD or imBTC.
* @return massetReturned Units of the underlying mAssets that were redeemed or swapped for the output tokens. eg mUSD or mBTC.
* @return outputQuantity Units of `output` tokens sent to the beneficiary.
*/
function redeemAndUnwrap(
uint256 _amount,
bool _isCreditAmt,
uint256 _minAmountOut,
address _output,
address _beneficiary,
address _router,
bool _isBassetOut
)
external
override
returns (
uint256 creditsBurned,
uint256 massetReturned,
uint256 outputQuantity
)
{
require(_amount > 0, "Must withdraw something");
require(_output != address(0), "Output address is zero");
require(_beneficiary != address(0), "Beneficiary address is zero");
require(_router != address(0), "Router address is zero");
// Collect recent interest generated by basket and update exchange rate
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
// Ensure that the payout was sufficient
(creditsBurned, massetReturned) = _redeem(_amount, _isCreditAmt, false);
require(
_isCreditAmt ? creditsBurned == _amount : massetReturned == _amount,
"Invalid output"
);
// Approve wrapper to spend contract's underlying; just for this tx
underlying.approve(unwrapper, massetReturned);
// Unwrap the underlying into `output` and transfer to `beneficiary`
outputQuantity = IUnwrapper(unwrapper).unwrapAndSend(
_isBassetOut,
_router,
address(underlying),
_output,
massetReturned,
_minAmountOut,
_beneficiary
);
}
/**
* @dev Internally burn the credits and send the underlying to msg.sender
*/
function _redeem(
uint256 _amt,
bool _isCreditAmt,
bool _transferUnderlying
) internal returns (uint256 creditsBurned, uint256 massetReturned) {
// Centralise credit <> underlying calcs and minimise SLOAD count
uint256 credits_;
uint256 underlying_;
uint256 exchangeRate_;
// If the input is a credit amt, then calculate underlying payout and cache the exchangeRate
if (_isCreditAmt) {
credits_ = _amt;
(underlying_, exchangeRate_) = _creditsToUnderlying(_amt);
}
// If the input is in underlying, then calculate credits needed to burn
else {
underlying_ = _amt;
(credits_, exchangeRate_) = _underlyingToCredits(_amt);
}
_burnTransfer(
underlying_,
credits_,
msg.sender,
msg.sender,
exchangeRate_,
_transferUnderlying
);
emit CreditsRedeemed(msg.sender, credits_, underlying_);
return (credits_, underlying_);
}
struct ConnectorStatus {
// Limit is the max amount of units allowed in the connector
uint256 limit;
// Derived balance of the connector
uint256 inConnector;
}
/**
* @dev Derives the units of collateral held in the connector
* @param _data Struct containing data on balances
* @param _exchangeRate Current system exchange rate
* @return status Contains max amount of assets allowed in connector
*/
function _getConnectorStatus(CachedData memory _data, uint256 _exchangeRate)
internal
pure
returns (ConnectorStatus memory)
{
// Total units of underlying collateralised
uint256 totalCollat = _data.totalCredits.mulTruncate(_exchangeRate);
// Max amount of underlying that can be held in the connector
uint256 limit = totalCollat.mulTruncate(_data.fraction + 2e17);
// Derives amount of underlying present in the connector
uint256 inConnector = _data.rawBalance >= totalCollat ? 0 : totalCollat - _data.rawBalance;
return ConnectorStatus(limit, inConnector);
}
/***************************************
YIELD - E
****************************************/
/** @dev Modifier allowing only the designated poker to execute the fn */
modifier onlyPoker() {
require(msg.sender == poker, "Only poker can execute");
_;
}
/**
* @dev External poke function allows for the redistribution of collateral between here and the
* current connector, setting the ratio back to the defined optimal.
*/
function poke() external onlyPoker {
CachedData memory cachedData = _cacheData();
_poke(cachedData, false);
}
/**
* @dev Governance action to set the address of a new poker
* @param _newPoker Address of the new poker
*/
function setPoker(address _newPoker) external onlyGovernor {
require(_newPoker != address(0) && _newPoker != poker, "Invalid poker");
poker = _newPoker;
emit PokerUpdated(_newPoker);
}
/**
* @dev Governance action to set the percentage of assets that should be held
* in the connector.
* @param _fraction Percentage of assets that should be held there (where 20% == 2e17)
*/
function setFraction(uint256 _fraction) external onlyGovernor {
require(_fraction <= 5e17, "Fraction must be <= 50%");
fraction = _fraction;
CachedData memory cachedData = _cacheData();
_poke(cachedData, true);
emit FractionUpdated(_fraction);
}
/**
* @dev Governance action to set the address of a new connector, and move funds (if any) across.
* @param _newConnector Address of the new connector
*/
function setConnector(address _newConnector) external onlyGovernor {
// Withdraw all from previous by setting target = 0
CachedData memory cachedData = _cacheData();
cachedData.fraction = 0;
_poke(cachedData, true);
// Set new connector
CachedData memory cachedDataNew = _cacheData();
connector = IConnector(_newConnector);
_poke(cachedDataNew, true);
emit ConnectorUpdated(_newConnector);
}
/**
* @dev Governance action to perform an emergency withdraw of the assets in the connector,
* should it be the case that some or all of the liquidity is trapped in. This causes the total
* collateral in the system to go down, causing a hard refresh.
*/
function emergencyWithdraw(uint256 _withdrawAmount) external onlyGovernor {
// withdraw _withdrawAmount from connection
connector.withdraw(_withdrawAmount);
// reset the connector
connector = IConnector(address(0));
emit ConnectorUpdated(address(0));
// set fraction to 0
fraction = 0;
emit FractionUpdated(0);
// check total collateralisation of credits
CachedData memory data = _cacheData();
// use rawBalance as the remaining liquidity in the connector is now written off
_refreshExchangeRate(data.rawBalance, data.totalCredits, true);
emit EmergencyUpdate();
}
/***************************************
YIELD - I
****************************************/
/** @dev Internal poke function to keep the balance between connector and raw balance healthy */
function _poke(CachedData memory _data, bool _ignoreCadence) internal {
require(_data.totalCredits > 0, "Must have something to poke");
// 1. Verify that poke cadence is valid, unless this is a manual action by governance
uint256 currentTime = uint256(block.timestamp);
uint256 timeSinceLastPoke = currentTime - lastPoke;
require(_ignoreCadence || timeSinceLastPoke > POKE_CADENCE, "Not enough time elapsed");
lastPoke = currentTime;
// If there is a connector, check the balance and settle to the specified fraction %
IConnector connector_ = connector;
if (address(connector_) != address(0)) {
// 2. Check and verify new connector balance
uint256 lastBalance_ = lastBalance;
uint256 connectorBalance = connector_.checkBalance();
// Always expect the collateral in the connector to increase in value
require(connectorBalance >= lastBalance_, "Invalid yield");
if (connectorBalance > 0) {
// Validate the collection by ensuring that the APY is not ridiculous
_validateCollection(
connectorBalance,
connectorBalance - lastBalance_,
timeSinceLastPoke
);
}
// 3. Level the assets to Fraction (connector) & 100-fraction (raw)
uint256 sum = _data.rawBalance + connectorBalance;
uint256 ideal = sum.mulTruncate(_data.fraction);
// If there is not enough mAsset in the connector, then deposit
if (ideal > connectorBalance) {
uint256 deposit_ = ideal - connectorBalance;
underlying.approve(address(connector_), deposit_);
connector_.deposit(deposit_);
}
// Else withdraw, if there is too much mAsset in the connector
else if (connectorBalance > ideal) {
// If fraction == 0, then withdraw everything
if (ideal == 0) {
connector_.withdrawAll();
sum = IERC20(underlying).balanceOf(address(this));
} else {
connector_.withdraw(connectorBalance - ideal);
}
}
// Else ideal == connectorBalance (e.g. 0), do nothing
require(connector_.checkBalance() >= ideal, "Enforce system invariant");
// 4i. Refresh exchange rate and emit event
lastBalance = ideal;
_refreshExchangeRate(sum, _data.totalCredits, false);
emit Poked(lastBalance_, ideal, connectorBalance - lastBalance_);
} else {
// 4ii. Refresh exchange rate and emit event
lastBalance = 0;
_refreshExchangeRate(_data.rawBalance, _data.totalCredits, false);
emit PokedRaw();
}
}
/**
* @dev Internal fn to refresh the exchange rate, based on the sum of collateral and the number of credits
* @param _realSum Sum of collateral held by the contract
* @param _totalCredits Total number of credits in the system
* @param _ignoreValidation This is for use in the emergency situation, and ignores a decreasing exchangeRate
*/
function _refreshExchangeRate(
uint256 _realSum,
uint256 _totalCredits,
bool _ignoreValidation
) internal {
// Based on the current exchange rate, how much underlying is collateralised?
(uint256 totalCredited, ) = _creditsToUnderlying(_totalCredits);
// Require the amount of capital held to be greater than the previously credited units
require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase");
// Work out the new exchange rate based on the current capital
uint256 newExchangeRate = _calcExchangeRate(_realSum, _totalCredits);
exchangeRate = newExchangeRate;
emit ExchangeRateUpdated(
newExchangeRate,
_realSum > totalCredited ? _realSum - totalCredited : 0
);
}
/**
* FORKED DIRECTLY FROM SAVINGSMANAGER.sol
* ---------------------------------------
* @dev Validates that an interest collection does not exceed a maximum APY. If last collection
* was under 30 mins ago, simply check it does not exceed 10bps
* @param _newBalance New balance of the underlying
* @param _interest Increase in total supply since last collection
* @param _timeSinceLastCollection Seconds since last collection
*/
function _validateCollection(
uint256 _newBalance,
uint256 _interest,
uint256 _timeSinceLastCollection
) internal pure returns (uint256 extrapolatedAPY) {
// Protect against division by 0
uint256 protectedTime = StableMath.max(1, _timeSinceLastCollection);
uint256 oldSupply = _newBalance - _interest;
uint256 percentageIncrease = _interest.divPrecisely(oldSupply);
uint256 yearsSinceLastCollection = protectedTime.divPrecisely(SECONDS_IN_YEAR);
extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection);
if (protectedTime > 30 minutes) {
require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY");
} else {
require(percentageIncrease < 1e15, "Interest protected from inflating past 10 Bps");
}
}
/***************************************
VIEW - I
****************************************/
struct CachedData {
// SLOAD from 'fraction'
uint256 fraction;
// ERC20 balance of underlying, held by this contract
// underlying.balanceOf(address(this))
uint256 rawBalance;
// totalSupply()
uint256 totalCredits;
}
/**
* @dev Retrieves generic data to avoid duplicate SLOADs
*/
function _cacheData() internal view returns (CachedData memory) {
uint256 balance = underlying.balanceOf(address(this));
return CachedData(fraction, balance, totalSupply());
}
/**
* @dev Converts masset amount into credits based on exchange rate
* c = (masset / exchangeRate) + 1
*/
function _underlyingToCredits(uint256 _underlying)
internal
view
returns (uint256 credits, uint256 exchangeRate_)
{
// e.g. (1e20 * 1e18) / 1e18 = 1e20
// e.g. (1e20 * 1e18) / 14e17 = 7.1429e19
// e.g. 1 * 1e18 / 1e17 + 1 = 11 => 11 * 1e17 / 1e18 = 1.1e18 / 1e18 = 1
exchangeRate_ = exchangeRate;
credits = _underlying.divPrecisely(exchangeRate_) + 1;
}
/**
* @dev Works out a new exchange rate, given an amount of collateral and total credits
* e = underlying / (credits-1)
*/
function _calcExchangeRate(uint256 _totalCollateral, uint256 _totalCredits)
internal
pure
returns (uint256 _exchangeRate)
{
_exchangeRate = _totalCollateral.divPrecisely(_totalCredits - 1);
}
/**
* @dev Converts credit amount into masset based on exchange rate
* m = credits * exchangeRate
*/
function _creditsToUnderlying(uint256 _credits)
internal
view
returns (uint256 underlyingAmount, uint256 exchangeRate_)
{
// e.g. (1e20 * 1e18) / 1e18 = 1e20
// e.g. (1e20 * 14e17) / 1e18 = 1.4e20
exchangeRate_ = exchangeRate;
underlyingAmount = _credits.mulTruncate(exchangeRate_);
}
/*///////////////////////////////////////////////////////////////
IERC4626Vault
//////////////////////////////////////////////////////////////*/
/**
* @notice it must be an ERC-20 token contract. Must not revert.
*
* @return assetTokenAddress the address of the underlying asset token. eg mUSD or mBTC
*/
function asset() external view override returns (address assetTokenAddress) {
return address(underlying);
}
/**
* @return totalManagedAssets the total amount of the underlying asset tokens that is “managed” by Vault.
*/
function totalAssets() external view override returns (uint256 totalManagedAssets) {
return underlying.balanceOf(address(this));
}
/**
* @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met.
* @param assets The amount of underlying assets to be convert to vault shares.
* @return shares The amount of vault shares converted from the underlying assets.
*/
function convertToShares(uint256 assets) external view override returns (uint256 shares) {
(shares, ) = _underlyingToCredits(assets);
}
/**
* @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met.
* @param shares The amount of vault shares to be converted to the underlying assets.
* @return assets The amount of underlying assets converted from the vault shares.
*/
function convertToAssets(uint256 shares) external view override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
}
/**
* @notice The maximum number of underlying assets that caller can deposit.
* caller Account that the assets will be transferred from.
* @return maxAssets The maximum amount of underlying assets the caller can deposit.
*/
function maxDeposit(
address /** caller **/
) external pure override returns (uint256 maxAssets) {
maxAssets = type(uint256).max;
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be transferred.
* @return shares The amount of vault shares that will be minted.
*/
function previewDeposit(uint256 assets) external view override returns (uint256 shares) {
require(assets > 0, "Must deposit something");
(shares, ) = _underlyingToCredits(assets);
}
/**
* @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller.
* Credit amount is calculated as a ratio of deposit amount and exchange rate:
* credits = underlying / exchangeRate
* We will first update the internal exchange rate by collecting any interest generated on the underlying.
* Emits a {Deposit} event.
* @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC
* @param receiver The address to receive the Vault shares.
* @return shares Units of credits issued. eg imUSD or imBTC
*/
function deposit(uint256 assets, address receiver) external override returns (uint256 shares) {
shares = _transferAndMint(assets, receiver, true);
}
/**
*
* @notice Overloaded `deposit` method with an optional referrer address.
* @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC
* @param receiver Address to the new credits will be issued to.
* @param referrer Referrer address for this deposit.
* @return shares Units of credits issued. eg imUSD or imBTC
*/
function deposit(
uint256 assets,
address receiver,
address referrer
) external override returns (uint256 shares) {
shares = _transferAndMint(assets, receiver, true);
emit Referral(referrer, receiver, assets);
}
/**
* @notice The maximum number of vault shares that caller can mint.
* caller Account that the underlying assets will be transferred from.
* @return maxShares The maximum amount of vault shares the caller can mint.
*/
function maxMint(
address /* caller */
) external pure override returns (uint256 maxShares) {
maxShares = type(uint256).max;
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions.
* @param shares The amount of vault shares to be minted.
* @return assets The amount of underlying assests that will be transferred from the caller.
*/
function previewMint(uint256 shares) external view override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
return assets;
}
/**
* @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.
* Emits a {Deposit} event.
*
* @param shares The amount of vault shares to be minted.
* @param receiver The account the vault shares will be minted to.
* @return assets The amount of underlying assets that were transferred from the caller.
*/
function mint(uint256 shares, address receiver) external override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
_transferAndMint(assets, receiver, true);
}
/**
* @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller.
* @param shares The amount of vault shares to be minted.
* @param receiver The account the vault shares will be minted to.
* @param referrer Referrer address for this deposit.
* @return assets The amount of underlying assets that were transferred from the caller.
* Emits a {Deposit}, {Referral} events
*/
function mint(
uint256 shares,
address receiver,
address referrer
) external override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
_transferAndMint(assets, receiver, true);
emit Referral(referrer, receiver, assets);
}
/**
* @notice The maximum number of underlying assets that owner can withdraw.
* @param owner Address that owns the underlying assets.
* @return maxAssets The maximum amount of underlying assets the owner can withdraw.
*/
function maxWithdraw(address owner) external view override returns (uint256 maxAssets) {
(maxAssets, ) = _creditsToUnderlying(balanceOf(owner));
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions.
* @param assets The amount of underlying assets to be withdrawn.
* @return shares The amount of vault shares that will be burnt.
*/
function previewWithdraw(uint256 assets) external view override returns (uint256 shares) {
(shares, ) = _underlyingToCredits(assets);
}
/**
* @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver.
* Emits a {Withdraw} event.
*
* @param assets The amount of underlying assets to be withdrawn from the vault.
* @param receiver The account that the underlying assets will be transferred to.
* @param owner Account that owns the vault shares to be burnt.
* @return shares The amount of vault shares that were burnt.
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external override returns (uint256 shares) {
require(assets > 0, "Must withdraw something");
uint256 _exchangeRate;
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
(shares, _exchangeRate) = _underlyingToCredits(assets);
_burnTransfer(assets, shares, receiver, owner, _exchangeRate, true);
}
/**
* @notice it must return a limited value if owner is subject to some withdrawal limit or timelock. must return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. MAY be used in the previewRedeem or redeem methods for shares input parameter. must NOT revert.
*
* @param owner Address that owns the shares.
* @return maxShares Total number of shares that owner can redeem.
*/
function maxRedeem(address owner) external view override returns (uint256 maxShares) {
maxShares = balanceOf(owner);
}
/**
* @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions.
*
* @return assets the exact amount of underlying assets that would be withdrawn by the caller if redeeming a given exact amount of Vault shares using the redeem method
*/
function previewRedeem(uint256 shares) external view override returns (uint256 assets) {
(assets, ) = _creditsToUnderlying(shares);
return assets;
}
/**
* @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver.
* Emits a {Withdraw} event.
*
* @param shares The amount of vault shares to be burnt.
* @param receiver The account the underlying assets will be transferred to.
* @param owner The account that owns the vault shares to be burnt.
* @return assets The amount of underlying assets that were transferred to the receiver.
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external override returns (uint256 assets) {
require(shares > 0, "Must withdraw something");
uint256 _exchangeRate;
if (automateInterestCollection) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying));
}
(assets, _exchangeRate) = _creditsToUnderlying(shares);
_burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); //transferAssets=true
}
/*///////////////////////////////////////////////////////////////
INTERNAL DEPOSIT/MINT
//////////////////////////////////////////////////////////////*/
function _transferAndMint(
uint256 assets,
address receiver,
bool _collectInterest
) internal returns (uint256 shares) {
require(assets > 0, "Must deposit something");
require(receiver != address(0), "Invalid beneficiary address");
// Collect recent interest generated by basket and update exchange rate
IERC20 mAsset = underlying;
if (_collectInterest) {
ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset));
}
// Transfer tokens from sender to here
require(mAsset.transferFrom(msg.sender, address(this), assets), "Must receive tokens");
// Calc how many credits they receive based on currentRatio
(shares, ) = _underlyingToCredits(assets);
// add credits to ERC20 balances
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
emit SavingsDeposited(receiver, assets, shares);
}
/*///////////////////////////////////////////////////////////////
INTERNAL WITHDRAW/REDEEM
//////////////////////////////////////////////////////////////*/
function _burnTransfer(
uint256 assets,
uint256 shares,
address receiver,
address owner,
uint256 _exchangeRate,
bool transferAssets
) internal {
require(receiver != address(0), "Invalid beneficiary address");
// If caller is not the owner of the shares
uint256 allowed = allowance(owner, msg.sender);
if (msg.sender != owner && allowed != type(uint256).max) {
require(shares <= allowed, "Amount exceeds allowance");
_approve(owner, msg.sender, allowed - shares);
}
// Burn required shares from the owner FIRST
_burn(owner, shares);
// Optionally, transfer tokens from here to receiver
if (transferAssets) {
require(underlying.transfer(receiver, assets), "Must send tokens");
emit Withdraw(msg.sender, receiver, owner, assets, shares);
}
// If this withdrawal pushes the portion of stored collateral in the `connector` over a certain
// threshold (fraction + 20%), then this should trigger a _poke on the connector. This is to avoid
// a situation in which there is a rush on withdrawals for some reason, causing the connector
// balance to go up and thus having too large an exposure.
CachedData memory cachedData = _cacheData();
ConnectorStatus memory status = _getConnectorStatus(cachedData, _exchangeRate);
if (status.inConnector > status.limit) {
_poke(cachedData, false);
}
}
} | DEPRECATED but still backwards compatible -------------------------------------------- -------------------------------------------- | interface ISavingsContractV4 is IERC4626Vault {
function redeem(uint256 _amount) external returns (uint256 massetReturned);
function depositSavings(uint256 _amount, address _beneficiary)
external
function redeemAndUnwrap(
uint256 _amount,
bool _isCreditAmt,
uint256 _minAmountOut,
address _output,
address _beneficiary,
address _router,
bool _isBassetOut
)
external
returns (
uint256 creditsBurned,
uint256 massetRedeemed,
uint256 outputQuantity
);
function depositSavings(
uint256 _underlying,
address _beneficiary,
address _referrer
) external returns (uint256 creditsIssued);
function deposit(
uint256 assets,
address receiver,
address referrer
) external returns (uint256 shares);
function mint(
uint256 shares,
address receiver,
address referrer
) external returns (uint256 assets);
}
}
| 11,800,722 |
./partial_match/56/0x9D7fc625957e42f2095437111dAa42b2244B997F/sources/VSafeVaultController.sol | forward to vault and then call earnExtra() by its governance | function earn(address _token, uint _amount) external override onlyAuthorized {
address _strategy = getBestStrategy();
if (_strategy == address(0) || IStrategy(_strategy).baseToken() != _token) {
IERC20(_token).safeTransfer(address(vault), _amount);
IERC20(_token).safeTransfer(_strategy, _amount);
IStrategy(_strategy).deposit();
}
}
| 11,211,118 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IVaultStrategyDataStore.sol";
import "../interfaces/IVault.sol";
import "./roles/Governable.sol";
/// @notice This contract will allow governance and managers to configure strategies and withdraw queues for a vault.
/// This contract should be deployed first, and then the address of this contract should be used to deploy a vault.
/// Once the vaults & strategies are deployed, call `addStrategy` function to assign a strategy to a vault.
contract VaultStrategyDataStore is IVaultStrategyDataStore, Context, Governable {
using ERC165Checker for address;
/// @notice parameters associated with a strategy
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
address vault;
}
struct VaultStrategyConfig {
// save the vault address in the mapping too to allow us to check if the vaultStrategy is actually created
// it can also be used to validate if msg.sender if the vault itself
address vault;
address manager;
uint256 totalDebtRatio;
uint256 maxTotalDebtRatio;
address[] withdrawQueue;
address[] strategies;
}
event VaultManagerUpdated(address indexed _vault, address indexed _manager);
event StrategyAdded(
address indexed _vault,
address indexed _strategyAddress,
uint256 _debtRatio,
uint256 _minDebtPerHarvest,
uint256 _maxDebtPerHarvest,
uint256 _performanceFee
);
event WithdrawQueueUpdated(address indexed _vault, address[] _queue);
event StrategyDebtRatioUpdated(address indexed _vault, address indexed _strategy, uint256 _debtRatio);
event StrategyMinDebtPerHarvestUpdated(address indexed _vault, address indexed _strategy, uint256 _minDebtPerHarvest);
event StrategyMaxDebtPerHarvestUpdated(address indexed _vault, address indexed _strategy, uint256 _maxDebtPerHarvest);
event StrategyPerformanceFeeUpdated(address indexed _vault, address indexed _strategy, uint256 _performanceFee);
event StrategyMigrated(address indexed _vault, address indexed _old, address indexed _new);
event StrategyRevoked(address indexed _vault, address indexed _strategy);
event StrategyRemovedFromQueue(address indexed _vault, address indexed _strategy);
event StrategyAddedToQueue(address indexed _vault, address indexed _strategy);
event MaxTotalRatioUpdated(address indexed _vault, uint256 _maxTotalDebtRatio);
/// @notice The maximum basis points. 1 basis point is 0.01% and 100% is 10000 basis points
uint256 public constant MAX_BASIS_POINTS = 10_000;
uint256 public constant DEFAULT_MAX_TOTAL_DEBT_RATIO = 9500;
/// @notice maximum number of strategies allowed for the withdraw queue
uint256 public constant MAX_STRATEGIES_PER_VAULT = 20;
/// @notice vaults and their strategy-related configs
mapping(address => VaultStrategyConfig) internal configs;
/// @notice vaults and their strategies.
/// @dev Can't put into the {VaultStrategyConfig} struct because nested mappings can't be constructed
mapping(address => mapping(address => StrategyParams)) internal strategies;
// solhint-disable-next-line
constructor(address _governance) Governable(_governance) {}
/// @notice returns the performance fee for a strategy in basis points.
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy
/// @return performance fee in basis points (100 = 1%)
function strategyPerformanceFee(address _vault, address _strategy) external view returns (uint256) {
require(_vault != address(0) && _strategy != address(0), "invalid address");
if (_strategyExists(_vault, _strategy)) {
return strategies[_vault][_strategy].performanceFee;
} else {
return 0;
}
}
/// @notice returns the time when a strategy is added to a vault
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy
/// @return the time when the strategy is added to the vault. 0 means the strategy is not added to the vault.
function strategyActivation(address _vault, address _strategy) external view returns (uint256) {
require(_vault != address(0) && _strategy != address(0), "invalid address");
if (_strategyExists(_vault, _strategy)) {
return strategies[_vault][_strategy].activation;
} else {
return 0;
}
}
/// @notice returns the debt ratio for a strategy in basis points.
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy
/// @return debt ratio in basis points (100 = 1%). Total debt ratio of all strategies for a vault can not exceed the MaxTotalDebtRatio of the vault.
function strategyDebtRatio(address _vault, address _strategy) external view returns (uint256) {
require(_vault != address(0) && _strategy != address(0), "invalid address");
if (_strategyExists(_vault, _strategy)) {
return strategies[_vault][_strategy].debtRatio;
} else {
return 0;
}
}
/// @notice returns the minimum value that the strategy can borrow from the vault per harvest.
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy
/// @return minimum value the strategy should borrow from the vault per harvest
function strategyMinDebtPerHarvest(address _vault, address _strategy) external view returns (uint256) {
require(_vault != address(0) && _strategy != address(0), "invalid address");
if (_strategyExists(_vault, _strategy)) {
return strategies[_vault][_strategy].minDebtPerHarvest;
} else {
return 0;
}
}
/// @notice returns the maximum value that the strategy can borrow from the vault per harvest.
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy
/// @return maximum value the strategy should borrow from the vault per harvest
function strategyMaxDebtPerHarvest(address _vault, address _strategy) external view returns (uint256) {
require(_vault != address(0) && _strategy != address(0), "invalid address");
if (_strategyExists(_vault, _strategy)) {
return strategies[_vault][_strategy].maxDebtPerHarvest;
} else {
return type(uint256).max;
}
}
/// @notice returns the total debt ratio of all the strategies for the vault in basis points
/// @param _vault the address of the vault
/// @return the total debt ratio of all the strategies. Should never exceed the value of MaxTotalDebtRatio
function vaultTotalDebtRatio(address _vault) external view returns (uint256) {
require(_vault != address(0), "invalid vault");
if (_vaultExists(_vault)) {
return configs[_vault].totalDebtRatio;
} else {
return 0;
}
}
/// @notice returns the address of strategies that will be withdrawn from if the vault needs to withdraw
/// @param _vault the address of the vault
/// @return the address of strategies for withdraw. First strategies in the queue will be withdrawn first.
function withdrawQueue(address _vault) external view returns (address[] memory) {
require(_vault != address(0), "invalid vault");
if (_vaultExists(_vault)) {
return configs[_vault].withdrawQueue;
} else {
return new address[](0);
}
}
/// @notice returns the manager address of the vault. Could be address(0) if it's not set
/// @param _vault the address of the vault
/// @return the manager address of the vault
function vaultManager(address _vault) external view returns (address) {
require(_vault != address(0), "invalid vault");
if (_vaultExists(_vault)) {
return configs[_vault].manager;
} else {
return address(0);
}
}
/// @notice returns the maxTotalDebtRatio of the vault in basis points. It limits the maximum amount of funds that all strategies of the value can borrow.
/// @param _vault the address of the vault
/// @return the maxTotalDebtRatio config of the vault
function vaultMaxTotalDebtRatio(address _vault) external view returns (uint256) {
require(_vault != address(0), "invalid vault");
if (_vaultExists(_vault)) {
return configs[_vault].maxTotalDebtRatio;
} else {
return DEFAULT_MAX_TOTAL_DEBT_RATIO;
}
}
/// @notice returns the list of strategies used by the vault. Use `strategyDebtRatio` to query fund allocation for a strategy.
/// @param _vault the address of the vault
/// @return the strategies of the vault
function vaultStrategies(address _vault) external view returns (address[] memory) {
require(_vault != address(0), "invalid vault");
if (_vaultExists(_vault)) {
return configs[_vault].strategies;
} else {
return new address[](0);
}
}
/// @notice set the manager of the vault. Can only be called by the governance.
/// @param _vault the address of the vault
/// @param _manager the address of the manager for the vault
function setVaultManager(address _vault, address _manager) external onlyGovernance {
require(_vault != address(0), "invalid vault");
_initConfigsIfNeeded(_vault);
if (configs[_vault].manager != _manager) {
configs[_vault].manager = _manager;
emit VaultManagerUpdated(_vault, _manager);
}
}
/// @notice set the maxTotalDebtRatio of the value.
/// @param _vault the address of the vault
/// @param _maxTotalDebtRatio the maximum total debt ratio value in basis points. Can not exceed 10000 (100%).
function setMaxTotalDebtRatio(address _vault, uint256 _maxTotalDebtRatio) external {
require(_vault != address(0), "invalid vault");
_onlyGovernanceOrVaultManager(_vault);
require(_maxTotalDebtRatio <= MAX_BASIS_POINTS, "invalid value");
_initConfigsIfNeeded(_vault);
if (configs[_vault].maxTotalDebtRatio != _maxTotalDebtRatio) {
configs[_vault].maxTotalDebtRatio = _maxTotalDebtRatio;
emit MaxTotalRatioUpdated(_vault, _maxTotalDebtRatio);
}
}
/// @notice add the given strategy to the vault
/// @param _vault the address of the vault to add strategy to
/// @param _strategy the address of the strategy contract
/// @param _debtRatio the percentage of the asset in the vault that will be allocated to the strategy, in basis points (1 BP is 0.01%).
/// @param _minDebtPerHarvest lower limit on the increase of debt since last harvest
/// @param _maxDebtPerHarvest upper limit on the increase of debt since last harvest
/// @param _performanceFee the fee that the strategist will receive based on the strategy's performance. In basis points.
function addStrategy(
address _vault,
address _strategy,
uint256 _debtRatio,
uint256 _minDebtPerHarvest,
uint256 _maxDebtPerHarvest,
uint256 _performanceFee
) external {
_onlyGovernanceOrVaultManager(_vault);
require(_strategy != address(0), "strategy address is not valid");
require(_strategy.supportsInterface(type(IStrategy).interfaceId), "!strategy");
_initConfigsIfNeeded(_vault);
require(configs[_vault].withdrawQueue.length < MAX_STRATEGIES_PER_VAULT, "too many strategies");
require(strategies[_vault][_strategy].activation == 0, "strategy already added");
if (IStrategy(_strategy).vault() != address(0)) {
require(IStrategy(_strategy).vault() == _vault, "wrong vault");
}
require(_minDebtPerHarvest <= _maxDebtPerHarvest, "invalid minDebtPerHarvest value");
require(
configs[_vault].totalDebtRatio + _debtRatio <= configs[_vault].maxTotalDebtRatio,
"total debtRatio over limit"
);
require(_performanceFee <= MAX_BASIS_POINTS / 2, "invalid performance fee");
/* solhint-disable not-rely-on-time */
strategies[_vault][_strategy] = StrategyParams({
performanceFee: _performanceFee,
activation: block.timestamp,
debtRatio: _debtRatio,
minDebtPerHarvest: _minDebtPerHarvest,
maxDebtPerHarvest: _maxDebtPerHarvest,
vault: _vault
});
/* solhint-enable */
require(IVault(_vault).addStrategy(_strategy), "vault error");
if (IStrategy(_strategy).vault() == address(0)) {
IStrategy(_strategy).setVault(_vault);
}
emit StrategyAdded(_vault, _strategy, _debtRatio, _minDebtPerHarvest, _maxDebtPerHarvest, _performanceFee);
configs[_vault].totalDebtRatio += _debtRatio;
configs[_vault].withdrawQueue.push(_strategy);
configs[_vault].strategies.push(_strategy);
}
/// @notice update the performance fee of the given strategy
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy contract
/// @param _performanceFee the new performance fee in basis points
function updateStrategyPerformanceFee(
address _vault,
address _strategy,
uint256 _performanceFee
) external onlyGovernance {
_validateVaultExists(_vault); //the strategy should be added already means the vault should exist
_validateStrategy(_vault, _strategy);
require(_performanceFee <= MAX_BASIS_POINTS / 2, "invalid performance fee");
strategies[_vault][_strategy].performanceFee = _performanceFee;
emit StrategyPerformanceFeeUpdated(_vault, _strategy, _performanceFee);
}
/// @notice update the debt ratio for the given strategy
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy contract
/// @param _debtRatio the new debt ratio of the strategy in basis points
function updateStrategyDebtRatio(
address _vault,
address _strategy,
uint256 _debtRatio
) external {
_validateVaultExists(_vault);
// This could be called by the Vault itself to update the debt ratio when a strategy is not performing well
_onlyAdminOrVault(_vault);
_validateStrategy(_vault, _strategy);
_updateStrategyDebtRatio(_vault, _strategy, _debtRatio);
}
/// @notice update the minDebtHarvest for the given strategy
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy contract
/// @param _minDebtPerHarvest the new minDebtPerHarvest value
function updateStrategyMinDebtHarvest(
address _vault,
address _strategy,
uint256 _minDebtPerHarvest
) external {
_validateVaultExists(_vault);
_onlyGovernanceOrVaultManager(_vault);
_validateStrategy(_vault, _strategy);
require(strategies[_vault][_strategy].maxDebtPerHarvest >= _minDebtPerHarvest, "invalid minDebtPerHarvest");
strategies[_vault][_strategy].minDebtPerHarvest = _minDebtPerHarvest;
emit StrategyMinDebtPerHarvestUpdated(_vault, _strategy, _minDebtPerHarvest);
}
/// @notice update the maxDebtHarvest for the given strategy
/// @param _vault the address of the vault
/// @param _strategy the address of the strategy contract
/// @param _maxDebtPerHarvest the new maxDebtPerHarvest value
function updateStrategyMaxDebtHarvest(
address _vault,
address _strategy,
uint256 _maxDebtPerHarvest
) external {
_validateVaultExists(_vault);
_onlyGovernanceOrVaultManager(_vault);
_validateStrategy(_vault, _strategy);
require(strategies[_vault][_strategy].minDebtPerHarvest <= _maxDebtPerHarvest, "invalid maxDebtPerHarvest");
strategies[_vault][_strategy].maxDebtPerHarvest = _maxDebtPerHarvest;
emit StrategyMaxDebtPerHarvestUpdated(_vault, _strategy, _maxDebtPerHarvest);
}
/// @notice updates the withdrawalQueue to match the addresses and order specified by `queue`.
/// There can be fewer strategies than the maximum, as well as fewer than
/// the total number of strategies active in the vault.
/// This may only be called by governance or management.
/// @dev This is order sensitive, specify the addresses in the order in which
/// funds should be withdrawn (so `queue`[0] is the first Strategy withdrawn
/// from, `queue`[1] is the second, etc.)
/// This means that the least impactful Strategy (the Strategy that will have
/// its core positions impacted the least by having funds removed) should be
/// at `queue`[0], then the next least impactful at `queue`[1], and so on.
/// @param _vault the address of the vault
/// @param _queue The array of addresses to use as the new withdrawal queue. This is order sensitive.
function setWithdrawQueue(address _vault, address[] calldata _queue) external {
require(_vault != address(0), "invalid vault");
require(_queue.length <= MAX_STRATEGIES_PER_VAULT, "invalid queue size");
_onlyGovernanceOrVaultManager(_vault);
_initConfigsIfNeeded(_vault);
address[] storage withdrawQueue_ = configs[_vault].withdrawQueue;
uint256 oldQueueSize = withdrawQueue_.length;
for (uint256 i = 0; i < _queue.length; i++) {
address temp = _queue[i];
require(strategies[_vault][temp].activation > 0, "invalid queue");
if (i > withdrawQueue_.length - 1) {
withdrawQueue_.push(temp);
} else {
withdrawQueue_[i] = temp;
}
}
if (oldQueueSize > _queue.length) {
for (uint256 j = oldQueueSize; j > _queue.length; j--) {
withdrawQueue_.pop();
}
}
emit WithdrawQueueUpdated(_vault, _queue);
}
/// @notice add the strategy to the `withdrawQueue`
/// @dev the strategy will only be appended to the `withdrawQueue`
/// @param _vault the address of the vault
/// @param _strategy the strategy to add
function addStrategyToWithdrawQueue(address _vault, address _strategy) external {
_validateVaultExists(_vault);
_onlyGovernanceOrVaultManager(_vault);
_validateStrategy(_vault, _strategy);
VaultStrategyConfig storage config_ = configs[_vault];
require(config_.withdrawQueue.length + 1 <= MAX_STRATEGIES_PER_VAULT, "too many strategies");
for (uint256 i = 0; i < config_.withdrawQueue.length; i++) {
require(config_.withdrawQueue[i] != _strategy, "strategy already exist");
}
config_.withdrawQueue.push(_strategy);
emit StrategyAddedToQueue(_vault, _strategy);
}
/// @notice remove the strategy from the `withdrawQueue`
/// @dev we don't do this with revokeStrategy because it should still be possible to withdraw from the Strategy if it's unwinding.
/// @param _vault the address of the vault
/// @param _strategy the strategy to remove
function removeStrategyFromWithdrawQueue(address _vault, address _strategy) external {
_validateVaultExists(_vault);
_onlyGovernanceOrVaultManager(_vault);
_validateStrategy(_vault, _strategy);
VaultStrategyConfig storage config_ = configs[_vault];
uint256 i = 0;
for (i = 0; i < config_.withdrawQueue.length; i++) {
if (config_.withdrawQueue[i] == _strategy) {
break;
}
}
require(i < config_.withdrawQueue.length, "strategy does not exist");
for (uint256 j = i; j < config_.withdrawQueue.length - 1; j++) {
config_.withdrawQueue[j] = config_.withdrawQueue[j + 1];
}
config_.withdrawQueue.pop();
emit StrategyRemovedFromQueue(_vault, _strategy);
}
/// @notice Migrate a Strategy, including all assets from `oldVersion` to `newVersion`. This may only be called by governance.
/// @dev Strategy must successfully migrate all capital and positions to new Strategy, or else this will upset the balance of the Vault.
/// The new Strategy should be "empty" e.g. have no prior commitments to
/// this Vault, otherwise it could have issues.
/// @param _vault the address of the vault
/// @param _oldStrategy the existing strategy to migrate from
/// @param _newStrategy the new strategy to migrate to
function migrateStrategy(
address _vault,
address _oldStrategy,
address _newStrategy
) external onlyGovernance {
_validateVaultExists(_vault);
_validateStrategy(_vault, _oldStrategy);
require(_newStrategy != address(0), "invalid new strategy");
require(strategies[_vault][_newStrategy].activation == 0, "new strategy already exists");
require(_newStrategy.supportsInterface(type(IStrategy).interfaceId), "!strategy");
StrategyParams memory params = strategies[_vault][_oldStrategy];
_revokeStrategy(_vault, _oldStrategy);
// _revokeStrategy will reduce the debt ratio
configs[_vault].totalDebtRatio += params.debtRatio;
//vs_.strategies[_oldStrategy].totalDebt = 0;
strategies[_vault][_newStrategy] = StrategyParams({
performanceFee: params.performanceFee,
activation: params.activation,
debtRatio: params.debtRatio,
minDebtPerHarvest: params.minDebtPerHarvest,
maxDebtPerHarvest: params.maxDebtPerHarvest,
vault: params.vault
});
require(IVault(_vault).migrateStrategy(_oldStrategy, _newStrategy), "vault error");
emit StrategyMigrated(_vault, _oldStrategy, _newStrategy);
for (uint256 i = 0; i < configs[_vault].withdrawQueue.length; i++) {
if (configs[_vault].withdrawQueue[i] == _oldStrategy) {
configs[_vault].withdrawQueue[i] = _newStrategy;
}
}
for (uint256 j = 0; j < configs[_vault].strategies.length; j++) {
if (configs[_vault].strategies[j] == _oldStrategy) {
configs[_vault].strategies[j] = _newStrategy;
}
}
}
/// @notice Revoke a Strategy, setting its debt limit to 0 and preventing any future deposits.
/// 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.
/// This may only be called by governance, or the manager.
///
/// @param _vault the address of the vault
/// @param _strategy The Strategy to revoke.
function revokeStrategy(address _vault, address _strategy) external {
_onlyGovernanceOrVaultManager(_vault);
if (strategies[_vault][_strategy].debtRatio != 0) {
_revokeStrategy(_vault, _strategy);
}
}
/// @notice Note that a Strategy will only revoke itself during emergency shutdown.
/// This function will be invoked the strategy by itself.
/// The Strategy will call the vault first and the vault will then forward the request to this contract.
/// This is to keep the Strategy interface compatible with Yearn's
/// This should only be called by the vault itself.
/// @param _strategy the address of the strategy to revoke
function revokeStrategyByStrategy(address _strategy) external {
_validateVaultExists(_msgSender());
_validateStrategy(_msgSender(), _strategy);
if (strategies[_msgSender()][_strategy].debtRatio != 0) {
_revokeStrategy(_msgSender(), _strategy);
}
}
function _vaultExists(address _vault) internal view returns (bool) {
if (configs[_vault].vault == _vault) {
return true;
}
return false;
}
function _strategyExists(address _vault, address _strategy) internal view returns (bool) {
if (strategies[_vault][_strategy].vault == _vault) {
return true;
}
return false;
}
function _initConfigsIfNeeded(address _vault) internal {
if (configs[_vault].vault != _vault) {
configs[_vault] = VaultStrategyConfig({
vault: _vault,
manager: address(0),
maxTotalDebtRatio: DEFAULT_MAX_TOTAL_DEBT_RATIO,
totalDebtRatio: 0,
withdrawQueue: new address[](0),
strategies: new address[](0)
});
}
}
function _validateVaultExists(address _vault) internal view {
require(_vault != address(0), "invalid vault");
require(configs[_vault].vault == _vault, "no vault");
}
function _validateStrategy(address _vault, address _strategy) internal view {
require(strategies[_vault][_strategy].activation > 0, "invalid strategy");
}
/// @dev make sure the vault exists and msg.send is either the governance or the manager of the vault
/// could be an modifier as well, but using internal functions to reduce the code size
function _onlyGovernanceOrVaultManager(address _vault) internal view {
require((governance == _msgSender()) || (configs[_vault].manager == _msgSender()), "not authorised");
}
function _onlyAdminOrVault(address _vault) internal view {
require(
(governance == _msgSender()) ||
(configs[_vault].manager == _msgSender()) ||
(configs[_msgSender()].vault == _vault),
"not authorised"
);
}
function _updateStrategyDebtRatio(
address _vault,
address _strategy,
uint256 _debtRatio
) internal {
VaultStrategyConfig storage config_ = configs[_vault];
config_.totalDebtRatio = config_.totalDebtRatio - (strategies[_vault][_strategy].debtRatio);
strategies[_vault][_strategy].debtRatio = _debtRatio;
config_.totalDebtRatio = config_.totalDebtRatio + _debtRatio;
require(config_.totalDebtRatio <= config_.maxTotalDebtRatio, "debtRatio over limit");
emit StrategyDebtRatioUpdated(_vault, _strategy, _debtRatio);
}
function _revokeStrategy(address _vault, address _strategy) internal {
configs[_vault].totalDebtRatio = configs[_vault].totalDebtRatio - strategies[_vault][_strategy].debtRatio;
strategies[_vault][_strategy].debtRatio = 0;
emit StrategyRevoked(_vault, _strategy);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStrategy {
// *** Events *** //
event Harvested(uint256 _profit, uint256 _loss, uint256 _debtPayment, uint256 _debtOutstanding);
event StrategistUpdated(address _newStrategist);
event KeeperUpdated(address _newKeeper);
event MinReportDelayUpdated(uint256 _delay);
event MaxReportDelayUpdated(uint256 _delay);
event ProfitFactorUpdated(uint256 _profitFactor);
event DebtThresholdUpdated(uint256 _debtThreshold);
event EmergencyExitEnabled();
// *** The following functions are used by the Vault *** //
/// @notice returns the address of the token that the strategy wants
function want() external view returns (IERC20);
/// @notice the address of the Vault that the strategy belongs to
function vault() external view returns (address);
/// @notice if the strategy is active
function isActive() external view returns (bool);
/// @notice migrate the strategy to the new one
function migrate(address _newStrategy) external;
/// @notice withdraw the amount from the strategy
function withdraw(uint256 _amount) external returns (uint256);
/// @notice the amount of total assets managed by this strategy that should not account towards the TVL of the strategy
function delegatedAssets() external view returns (uint256);
/// @notice the total assets that the strategy is managing
function estimatedTotalAssets() external view returns (uint256);
// *** public read functions that can be called by anyone *** //
function name() external view returns (string memory);
function harvester() external view returns (address);
function strategyProposer() external view returns (address);
function strategyDeveloper() external view returns (address);
function tendTrigger(uint256 _callCost) external view returns (bool);
function harvestTrigger(uint256 _callCost) external view returns (bool);
// *** write functions that can be called by the governance, the strategist or the keeper *** //
function tend() external;
function harvest() external;
// *** write functions that can be called by the governance or the strategist ***//
function setHarvester(address _havester) external;
function setVault(address _vault) external;
/// @notice `minReportDelay` is the minimum number of blocks that should pass for `harvest()` to be called.
function setMinReportDelay(uint256 _delay) external;
function setMaxReportDelay(uint256 _delay) external;
/// @notice `profitFactor` is used to determine if it's worthwhile to harvest, given gas costs.
function setProfitFactor(uint256 _profitFactor) external;
/// @notice Sets how far the Strategy can go into loss without a harvest and report being required.
function setDebtThreshold(uint256 _debtThreshold) external;
// *** write functions that can be called by the governance, or the strategist, or the guardian, or the management *** //
function setEmergencyExit() external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface IVaultStrategyDataStore {
function strategyPerformanceFee(address _vault, address _strategy) external view returns (uint256);
function strategyActivation(address _vault, address _strategy) external view returns (uint256);
function strategyDebtRatio(address _vault, address _strategy) external view returns (uint256);
function strategyMinDebtPerHarvest(address _vault, address _strategy) external view returns (uint256);
function strategyMaxDebtPerHarvest(address _vault, address _strategy) external view returns (uint256);
function vaultStrategies(address _vault) external view returns (address[] memory);
function vaultTotalDebtRatio(address _vault) external view returns (uint256);
function withdrawQueue(address _vault) external view returns (address[] memory);
function revokeStrategyByStrategy(address _strategy) external;
function setVaultManager(address _vault, address _manager) external;
function setMaxTotalDebtRatio(address _vault, uint256 _maxTotalDebtRatio) external;
function addStrategy(
address _vault,
address _strategy,
uint256 _debtRatio,
uint256 _minDebtPerHarvest,
uint256 _maxDebtPerHarvest,
uint256 _performanceFee
) external;
function updateStrategyPerformanceFee(
address _vault,
address _strategy,
uint256 _performanceFee
) external;
function updateStrategyDebtRatio(
address _vault,
address _strategy,
uint256 _debtRatio
) external;
function updateStrategyMinDebtHarvest(
address _vault,
address _strategy,
uint256 _minDebtPerHarvest
) external;
function updateStrategyMaxDebtHarvest(
address _vault,
address _strategy,
uint256 _maxDebtPerHarvest
) external;
function migrateStrategy(
address _vault,
address _oldStrategy,
address _newStrategy
) external;
function revokeStrategy(address _vault, address _strategy) external;
function setWithdrawQueue(address _vault, address[] calldata _queue) external;
function addStrategyToWithdrawQueue(address _vault, address _strategy) external;
function removeStrategyFromWithdrawQueue(address _vault, address _strategy) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
struct StrategyInfo {
uint256 activation;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
interface IVault is IERC20, IERC20Permit {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256);
function activation() external view returns (uint256);
function rewards() external view returns (address);
function managementFee() external view returns (uint256);
function gatekeeper() external view returns (address);
function governance() external view returns (address);
function creator() external view returns (address);
function strategyDataStore() external view returns (address);
function healthCheck() external view returns (address);
function emergencyShutdown() external view returns (bool);
function lockedProfitDegradation() external view returns (uint256);
function depositLimit() external view returns (uint256);
function lastReport() external view returns (uint256);
function lockedProfit() external view returns (uint256);
function totalDebt() external view returns (uint256);
function token() external view returns (address);
function totalAsset() external view returns (uint256);
function availableDepositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
function pricePerShare() external view returns (uint256);
function debtOutstanding(address _strategy) external view returns (uint256);
function creditAvailable(address _strategy) external view returns (uint256);
function expectedReturn(address _strategy) external view returns (uint256);
function strategy(address _strategy) external view returns (StrategyInfo memory);
function strategyDebtRatio(address _strategy) external view returns (uint256);
function setRewards(address _rewards) external;
function setManagementFee(uint256 _managementFee) external;
function setGatekeeper(address _gatekeeper) external;
function setStrategyDataStore(address _strategyDataStoreContract) external;
function setHealthCheck(address _healthCheck) external;
function setVaultEmergencyShutdown(bool _active) external;
function setLockedProfileDegradation(uint256 _degradation) external;
function setDepositLimit(uint256 _limit) external;
function sweep(address _token, uint256 _amount) external;
function addStrategy(address _strategy) external returns (bool);
function migrateStrategy(address _oldVersion, address _newVersion) external returns (bool);
function revokeStrategy() external;
/// @notice deposit the given amount into the vault, and return the number of shares
function deposit(uint256 _amount, address _recipient) external returns (uint256);
/// @notice burn the given amount of shares from the vault, and return the number of underlying tokens recovered
function withdraw(
uint256 _shares,
address _recipient,
uint256 _maxLoss
) external returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
interface IGovernable {
function proposeGovernance(address _pendingGovernance) external;
function acceptGovernance() external;
}
abstract contract GovernableInternal {
event GovenanceUpdated(address _govenance);
event GovenanceProposed(address _pendingGovenance);
/// @dev This contract is used as part of the Vault contract and it is upgradeable.
/// which means any changes to the state variables could corrupt the data. Do not modify these at all.
/// @notice the address of the current governance
address public governance;
/// @notice the address of the pending governance
address public pendingGovernance;
/// @dev ensure msg.send is the governanace
modifier onlyGovernance() {
require(_getMsgSender() == governance, "governance only");
_;
}
/// @dev ensure msg.send is the pendingGovernance
modifier onlyPendingGovernance() {
require(_getMsgSender() == pendingGovernance, "pending governance only");
_;
}
/// @dev the deployer of the contract will be set as the initial governance
// solhint-disable-next-line func-name-mixedcase
function __Governable_init_unchained(address _governance) internal {
require(_getMsgSender() != _governance, "invalid address");
_updateGovernance(_governance);
}
///@notice propose a new governance of the vault. Only can be called by the existing governance.
///@param _pendingGovernance the address of the pending governance
function proposeGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "invalid address");
require(_pendingGovernance != governance, "already the governance");
pendingGovernance = _pendingGovernance;
emit GovenanceProposed(_pendingGovernance);
}
///@notice accept the proposal to be the governance of the vault. Only can be called by the pending governance.
function acceptGovernance() external onlyPendingGovernance {
_updateGovernance(pendingGovernance);
}
function _updateGovernance(address _pendingGovernance) internal {
governance = _pendingGovernance;
emit GovenanceUpdated(governance);
}
/// @dev provides an internal function to allow reduce the contract size
function _onlyGovernance() internal view {
require(_getMsgSender() == governance, "governance only");
}
function _getMsgSender() internal view virtual returns (address);
}
/// @dev Add a `governance` and a `pendingGovernance` role to the contract, and implements a 2-phased nominatiom process to change the governance.
/// Also provides a modifier to allow controlling access to functions of the contract.
contract Governable is Context, GovernableInternal {
constructor(address _governance) GovernableInternal() {
__Governable_init_unchained(_governance);
}
function _getMsgSender() internal view override returns (address) {
return _msgSender();
}
}
/// @dev ungradeable version of the {Governable} contract. Can be used as part of an upgradeable contract.
abstract contract GovernableUpgradeable is ContextUpgradeable, GovernableInternal {
// solhint-disable-next-line no-empty-blocks
constructor() {}
// solhint-disable-next-line func-name-mixedcase
function __Governable_init(address _governance) internal {
__Context_init();
__Governable_init_unchained(_governance);
}
// solhint-disable-next-line func-name-mixedcase
function _getMsgSender() internal view override returns (address) {
return _msgSender();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | returns the maximum value that the strategy can borrow from the vault per harvest. _vault the address of the vault _strategy the address of the strategy return maximum value the strategy should borrow from the vault per harvest | function strategyMaxDebtPerHarvest(address _vault, address _strategy) external view returns (uint256) {
require(_vault != address(0) && _strategy != address(0), "invalid address");
if (_strategyExists(_vault, _strategy)) {
return strategies[_vault][_strategy].maxDebtPerHarvest;
return type(uint256).max;
}
}
| 12,031,986 |
pragma solidity 0.5.16;
// INTERFACE
interface IERC20Mintable {
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function mint(address _to, uint256 _value) external returns (bool);
function balanceOf(address _account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
/**
* @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);
}
// LIB
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
return int64(x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
require(x >= 0);
return uint64(x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128(int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128(int128 x) internal pure returns (int256) {
return int256(x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli(int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require(
y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000
);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu(x, uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require(x >= 0);
uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(x) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div(int128 x, int128 y) internal pure returns (int128) {
require(y != 0);
int256 result = (int256(x) << 64) / y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi(int256 x, int256 y) internal pure returns (int128) {
require(y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu(uint256(x), uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg(int128 x) internal pure returns (int128) {
require(x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs(int128 x) internal pure returns (int128) {
require(x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg(int128 x, int128 y) internal pure returns (int128) {
return int128((int256(x) + int256(y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg(int128 x, int128 y) internal pure returns (int128) {
int256 m = int256(x) * int256(y);
require(m >= 0);
require(m < 0x4000000000000000000000000000000000000000000000000000000000000000);
return int128(sqrtu(uint256(m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128(x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x2 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x4 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x8 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) {
absX <<= 32;
absXShift -= 32;
}
if (absX < 0x10000000000000000000000000000) {
absX <<= 16;
absXShift -= 16;
}
if (absX < 0x1000000000000000000000000000000) {
absX <<= 8;
absXShift -= 8;
}
if (absX < 0x10000000000000000000000000000000) {
absX <<= 4;
absXShift -= 4;
}
if (absX < 0x40000000000000000000000000000000) {
absX <<= 2;
absXShift -= 2;
}
if (absX < 0x80000000000000000000000000000000) {
absX <<= 1;
absXShift -= 1;
}
uint256 resultShift = 0;
while (y != 0) {
require(absXShift < 64);
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = (absX * absX) >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require(resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256(absResult) : int256(absResult);
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt(int128 x) internal pure returns (int128) {
require(x >= 0);
return int128(sqrtu(uint256(x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(int128 x) internal pure returns (int128) {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(x) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
require(x > 0);
return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2(int128 x) internal pure returns (int128) {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(63 - (x >> 64));
require(result <= uint256(MAX_64x64));
return int128(result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp(int128 x) internal pure returns (int128) {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2(int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant POSITIVE_ZERO = 0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt(int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt(bytes16 x) internal pure returns (int256) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(result);
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt(uint256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
uint256 result = x;
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16383 + msb) << 112);
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt(bytes16 x) internal pure returns (uint256) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require(uint128(x) < 0x80000000000000000000000000000000); // Negative
require(exponent <= 16638); // Overflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128(int256 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16255 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128(bytes16 x) internal pure returns (int256) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256(result);
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64(int128 x) internal pure returns (bytes16) {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint128(x > 0 ? x : -x);
uint256 msb = msb(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result = (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | ((16319 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64(bytes16 x) internal pure returns (int128) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000);
return -int128(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(result);
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple(bytes32 x) internal pure returns (bytes16) {
bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0;
uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;
uint256 significand = uint256(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
}
if (exponent > 278526) return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else if (exponent < 245649) return negative ? NEGATIVE_ZERO : POSITIVE_ZERO;
else if (exponent < 245761) {
significand =
(significand | 0x100000000000000000000000000000000000000000000000000000000000) >>
(245885 - exponent);
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128(significand | (exponent << 112));
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16(result);
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple(bytes16 x) internal pure returns (bytes32) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb(result);
result = (result << (236 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble(bytes8 x) internal pure returns (bytes16) {
uint256 exponent = (uint64(x) >> 52) & 0x7FF;
uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF)
exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = msb(result);
result = (result << (112 - msb)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble(bytes16 x) internal pure returns (bytes8) {
bool negative = uint128(x) >= 0x80000000000000000000000000000000;
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000;
// NaN
else
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000);
// Infinity
else if (exponent < 15309)
return
negative
? bytes8(0x8000000000000000) // -0
: bytes8(0x0000000000000000);
// 0
else if (exponent < 15361) {
significand = (significand | 0x10000000000000000000000000000) >> (15421 - exponent);
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64(significand | (exponent << 52));
if (negative) result |= 0x8000000000000000;
return bytes8(result);
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN(bytes16 x) internal pure returns (bool) {
return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF > 0x7FFF0000000000000000000000000000;
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity(bytes16 x) internal pure returns (bool) {
return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x7FFF0000000000000000000000000000;
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign(bytes16 x) internal pure returns (int8) {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128(x) >= 0x80000000000000000000000000000000) return -1;
else return 1;
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX = uint128(x) >= 0x80000000000000000000000000000000;
bool negativeY = uint128(y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8(1) : -1;
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
if (x == y) {
return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF < 0x7FFF0000000000000000000000000000;
} else return false;
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return y == NEGATIVE_ZERO ? POSITIVE_ZERO : y;
else if (ySignifier == 0) return x == NEGATIVE_ZERO ? POSITIVE_ZERO : x;
else {
int256 delta = int256(xExponent) - int256(yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256(delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256(-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF) return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000) xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return
bytes16(
uint128(
(xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier
)
);
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1) ySignifier = ((ySignifier - 1) >> uint256(delta - 1)) + 1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1) xSignifier = ((xSignifier - 1) >> uint256(-delta - 1)) + 1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0) return POSITIVE_ZERO;
uint256 msb = msb(xSignifier);
if (msb == 113) {
xSignifier = (xSignifier >> 1) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier = (xSignifier << shift) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF) return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
else
return
bytes16(
uint128(
(xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier
)
);
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
return add(x, y ^ 0x80000000000000000000000000000000);
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x ^ (y & 0x80000000000000000000000000000000);
else if (x ^ y == 0x80000000000000000000000000000000) return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ (x & 0x80000000000000000000000000000000);
} else {
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb = xSignifier >= 0x200000000000000000000000000000000000000000000000000000000
? 225
: xSignifier >= 0x100000000000000000000000000000000000000000000000000000000
? 224
: msb(xSignifier);
if (xExponent + msb < 16496) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) {
// Subnormal
if (xExponent < 16496) xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496) xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112) xSignifier >>= msb - 112;
else if (msb < 112) xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return
bytes16(
uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | (xExponent << 112) | xSignifier)
);
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else return POSITIVE_ZERO | ((x ^ y) & 0x80000000000000000000000000000000);
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return POSITIVE_INFINITY | ((x ^ y) & 0x80000000000000000000000000000000);
} else {
uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint256 shift = 226 - msb(xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
} else {
xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO;
assert(xSignifier >= 0x1000000000000000000000000000);
uint256 msb = xSignifier >= 0x80000000000000000000000000000
? msb(xSignifier)
: xSignifier >= 0x40000000000000000000000000000
? 114
: xSignifier >= 0x20000000000000000000000000000
? 113
: 112;
if (xExponent + msb > yExponent + 16497) {
// Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) {
// Subnormal
if (xExponent + 16380 > yExponent) xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent) xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else {
// Normal
if (msb > 112) xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return
bytes16(
uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | (xExponent << 112) | xSignifier)
);
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg(bytes16 x) internal pure returns (bytes16) {
return x ^ 0x80000000000000000000000000000000;
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs(bytes16 x) internal pure returns (bytes16) {
return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt(bytes16 x) internal pure returns (bytes16) {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = (xExponent + 16383) >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 113;
else {
uint256 msb = msb(xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 112;
else {
uint256 msb = msb(xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return bytes16(uint128((xExponent << 112) | (r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)));
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2(bytes16 x) internal pure returns (bytes16) {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000) return POSITIVE_ZERO;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = msb(xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift = 112 - msb(resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (resultSignifier < 0x10000000000000000000000000000) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return
bytes16(
uint128(
(resultNegative ? 0x80000000000000000000000000000000 : 0) |
(resultExponent << 112) |
(resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln(bytes16 x) internal pure returns (bytes16) {
return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2(bytes16 x) internal pure returns (bytes16) {
bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397) return xNegative ? POSITIVE_ZERO : POSITIVE_INFINITY;
else if (xExponent < 16255) return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367) xSignifier <<= xExponent - 16367;
else if (xExponent < 16367) xSignifier >>= 16367 - xExponent;
if (xNegative && xSignifier > 0x406E00000000000000000000000000000000) return POSITIVE_ZERO;
if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (xSignifier & 0x40000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (xSignifier & 0x20000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (xSignifier & 0x10000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (xSignifier & 0x8000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (xSignifier & 0x4000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (xSignifier & 0x2000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (xSignifier & 0x1000000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (xSignifier & 0x800000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (xSignifier & 0x400000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (xSignifier & 0x200000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (xSignifier & 0x100000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (xSignifier & 0x80000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (xSignifier & 0x40000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (xSignifier & 0x20000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000162E525EE054754457D5995292026) >> 128;
if (xSignifier & 0x10000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (xSignifier & 0x8000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (xSignifier & 0x4000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (xSignifier & 0x2000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (xSignifier & 0x1000000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (xSignifier & 0x800000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (xSignifier & 0x400000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (xSignifier & 0x200000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (xSignifier & 0x100000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (xSignifier & 0x80000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (xSignifier & 0x40000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (xSignifier & 0x20000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (xSignifier & 0x10000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (xSignifier & 0x8000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (xSignifier & 0x4000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (xSignifier & 0x2000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (xSignifier & 0x1000000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (xSignifier & 0x800000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (xSignifier & 0x400000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (xSignifier & 0x200000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (xSignifier & 0x100000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (xSignifier & 0x80000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (xSignifier & 0x40000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (xSignifier & 0x20000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (xSignifier & 0x10000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (xSignifier & 0x8000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (xSignifier & 0x4000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (xSignifier & 0x2000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (xSignifier & 0x1000000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (xSignifier & 0x800000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (xSignifier & 0x400000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (xSignifier & 0x200000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (xSignifier & 0x100000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (xSignifier & 0x80000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (xSignifier & 0x40000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (xSignifier & 0x20000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (xSignifier & 0x10000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (xSignifier & 0x8000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (xSignifier & 0x4000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (xSignifier & 0x2000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (xSignifier & 0x1000000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (xSignifier & 0x800000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (xSignifier & 0x400000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (xSignifier & 0x200000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (xSignifier & 0x100000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (xSignifier & 0x80000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (xSignifier & 0x40000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (xSignifier & 0x20000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (xSignifier & 0x10000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000B17217F7D1CF79AB) >> 128;
if (xSignifier & 0x8000000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5) >> 128;
if (xSignifier & 0x4000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000002C5C85FDF473DE6A) >> 128;
if (xSignifier & 0x2000000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000162E42FEFA39EF34) >> 128;
if (xSignifier & 0x1000000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000B17217F7D1CF799) >> 128;
if (xSignifier & 0x800000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000058B90BFBE8E7BCC) >> 128;
if (xSignifier & 0x400000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000002C5C85FDF473DE5) >> 128;
if (xSignifier & 0x200000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000162E42FEFA39EF2) >> 128;
if (xSignifier & 0x100000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000B17217F7D1CF78) >> 128;
if (xSignifier & 0x80000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000058B90BFBE8E7BB) >> 128;
if (xSignifier & 0x40000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000002C5C85FDF473DD) >> 128;
if (xSignifier & 0x20000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000162E42FEFA39EE) >> 128;
if (xSignifier & 0x10000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000B17217F7D1CF6) >> 128;
if (xSignifier & 0x8000000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000058B90BFBE8E7A) >> 128;
if (xSignifier & 0x4000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000002C5C85FDF473C) >> 128;
if (xSignifier & 0x2000000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000162E42FEFA39D) >> 128;
if (xSignifier & 0x1000000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000B17217F7D1CE) >> 128;
if (xSignifier & 0x800000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000058B90BFBE8E6) >> 128;
if (xSignifier & 0x400000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000002C5C85FDF472) >> 128;
if (xSignifier & 0x200000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000162E42FEFA38) >> 128;
if (xSignifier & 0x100000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000B17217F7D1B) >> 128;
if (xSignifier & 0x80000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000058B90BFBE8D) >> 128;
if (xSignifier & 0x40000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000002C5C85FDF46) >> 128;
if (xSignifier & 0x20000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000162E42FEFA2) >> 128;
if (xSignifier & 0x10000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000B17217F7D0) >> 128;
if (xSignifier & 0x8000000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000058B90BFBE7) >> 128;
if (xSignifier & 0x4000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000002C5C85FDF3) >> 128;
if (xSignifier & 0x2000000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000162E42FEF9) >> 128;
if (xSignifier & 0x1000000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000B17217F7C) >> 128;
if (xSignifier & 0x800000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000058B90BFBD) >> 128;
if (xSignifier & 0x400000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000002C5C85FDE) >> 128;
if (xSignifier & 0x200000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000162E42FEE) >> 128;
if (xSignifier & 0x100000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000B17217F6) >> 128;
if (xSignifier & 0x80000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000058B90BFA) >> 128;
if (xSignifier & 0x40000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000002C5C85FC) >> 128;
if (xSignifier & 0x20000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000162E42FD) >> 128;
if (xSignifier & 0x10000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000B17217E) >> 128;
if (xSignifier & 0x8000000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000058B90BE) >> 128;
if (xSignifier & 0x4000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000002C5C85E) >> 128;
if (xSignifier & 0x2000000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000162E42E) >> 128;
if (xSignifier & 0x1000000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000B17216) >> 128;
if (xSignifier & 0x800000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000058B90A) >> 128;
if (xSignifier & 0x400000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000002C5C84) >> 128;
if (xSignifier & 0x200000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000162E41) >> 128;
if (xSignifier & 0x100000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000B1720) >> 128;
if (xSignifier & 0x80000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000058B8F) >> 128;
if (xSignifier & 0x40000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000002C5C7) >> 128;
if (xSignifier & 0x20000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000162E3) >> 128;
if (xSignifier & 0x10000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000000B171) >> 128;
if (xSignifier & 0x8000 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000058B8) >> 128;
if (xSignifier & 0x4000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000002C5B) >> 128;
if (xSignifier & 0x2000 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000000162D) >> 128;
if (xSignifier & 0x1000 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000000B16) >> 128;
if (xSignifier & 0x800 > 0)
resultSignifier = (resultSignifier * 0x10000000000000000000000000000058A) >> 128;
if (xSignifier & 0x400 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000002C4) >> 128;
if (xSignifier & 0x200 > 0)
resultSignifier = (resultSignifier * 0x100000000000000000000000000000161) >> 128;
if (xSignifier & 0x100 > 0)
resultSignifier = (resultSignifier * 0x1000000000000000000000000000000B0) >> 128;
if (xSignifier & 0x80 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000057) >> 128;
if (xSignifier & 0x40 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000002B) >> 128;
if (xSignifier & 0x20 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000015) >> 128;
if (xSignifier & 0x10 > 0) resultSignifier = (resultSignifier * 0x10000000000000000000000000000000A) >> 128;
if (xSignifier & 0x8 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000004) >> 128;
if (xSignifier & 0x4 > 0) resultSignifier = (resultSignifier * 0x100000000000000000000000000000001) >> 128;
if (!xNegative) {
resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier = (resultSignifier >> 15) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier = resultSignifier >> (resultExponent - 16367);
resultExponent = 0;
}
return bytes16(uint128((resultExponent << 112) | resultSignifier));
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp(bytes16 x) internal pure returns (bytes16) {
return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function msb(uint256 x) private pure returns (uint256) {
require(x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
result += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
result += 64;
}
if (x >= 0x100000000) {
x >>= 32;
result += 32;
}
if (x >= 0x10000) {
x >>= 16;
result += 16;
}
if (x >= 0x100) {
x >>= 8;
result += 8;
}
if (x >= 0x10) {
x >>= 4;
result += 4;
}
if (x >= 0x4) {
x >>= 2;
result += 2;
}
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
// CONTRACTS
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract Sacrifice {
constructor(address payable _recipient) public payable {
selfdestruct(_recipient);
}
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// 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");
}
uint256[50] private ______gap;
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMathERC20 {
function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/*
* @dev 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.
*/
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = 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 _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
contract StakingV2 is Ownable, ReentrancyGuard {
using Address for address;
using SafeMath for uint256;
using SafeERC20 for IERC20;
// EVENTS
/**
* @dev Emitted when a user deposits tokens.
* @param sender User address.
* @param id User's unique deposit ID.
* @param amount The amount of deposited tokens.
* @param currentBalance Current user balance.
* @param timestamp Operation date
*/
event Deposited(
address indexed sender,
uint256 indexed id,
uint256 amount,
uint256 currentBalance,
uint256 timestamp
);
/**
* @dev Emitted when a user withdraws tokens.
* @param sender User address.
* @param id User's unique deposit ID.
* @param totalWithdrawalAmount The total amount of withdrawn tokens.
* @param currentBalance Balance before withdrawal
* @param timestamp Operation date
*/
event WithdrawnAll(
address indexed sender,
uint256 indexed id,
uint256 totalWithdrawalAmount,
uint256 currentBalance,
uint256 timestamp
);
/**
* @dev Emitted when a user extends lockup.
* @param sender User address.
* @param id User's unique deposit ID.
* @param currentBalance Balance before lockup extension
* @param finalBalance Final balance
* @param timestamp The instant when the lockup is extended.
*/
event ExtendedLockup(
address indexed sender,
uint256 indexed id,
uint256 currentBalance,
uint256 finalBalance,
uint256 timestamp
);
/**
* @dev Emitted when a new Liquidity Provider address value is set.
* @param value A new address value.
* @param sender The owner address at the moment of address changing.
*/
event LiquidityProviderAddressSet(address value, address sender);
struct AddressParam {
address oldValue;
address newValue;
uint256 timestamp;
}
// The deposit user balaces
mapping(address => mapping(uint256 => uint256)) public balances;
// The dates of users deposits/withdraws/extendLockups
mapping(address => mapping(uint256 => uint256)) public depositDates;
// Variable that prevents _deposit method from being called 2 times TODO CHECK
bool private locked;
// Variable to pause all operations
bool private contractPaused = false;
bool private pausedDepositsAndLockupExtensions = false;
// STAKE token
IERC20Mintable public token;
// Reward Token
IERC20Mintable public tokenReward;
// The address for the Liquidity Providers
AddressParam public liquidityProviderAddressParam;
uint256 private constant DAY = 1 days;
uint256 private constant MONTH = 30 days;
uint256 private constant YEAR = 365 days;
// The period after which the new value of the parameter is set
uint256 public constant PARAM_UPDATE_DELAY = 7 days;
// MODIFIERS
/*
* 1 | 2 | 3 | 4 | 5
* 0 Months | 3 Months | 6 Months | 9 Months | 12 Months
*/
modifier validDepositId(uint256 _depositId) {
require(_depositId >= 1 && _depositId <= 5, "Invalid depositId");
_;
}
// Impossible to withdrawAll if you have never deposited.
modifier balanceExists(uint256 _depositId) {
require(balances[msg.sender][_depositId] > 0, "Your deposit is zero");
_;
}
modifier isNotLocked() {
require(locked == false, "Locked, try again later");
_;
}
modifier isNotPaused() {
require(contractPaused == false, "Paused");
_;
}
modifier isNotPausedOperations() {
require(contractPaused == false, "Paused");
_;
}
modifier isNotPausedDepositAndLockupExtensions() {
require(pausedDepositsAndLockupExtensions == false, "Paused Deposits and Extensions");
_;
}
/**
* @dev Pause Deposits, Withdraw, Lockup Extension
*/
function pauseContract(bool value) public onlyOwner {
contractPaused = value;
}
/**
* @dev Pause Deposits and Lockup Extension
*/
function pauseDepositAndLockupExtensions(bool value) public onlyOwner {
pausedDepositsAndLockupExtensions = value;
}
/**
* @dev Initializes the contract. _tokenAddress _tokenReward will have the same address
* @param _owner The owner of the contract.
* @param _tokenAddress The address of the STAKE token contract.
* @param _tokenReward The address of token rewards.
* @param _liquidityProviderAddress The address for the Liquidity Providers reward.
*/
function initializeStaking(
address _owner,
address _tokenAddress,
address _tokenReward,
address _liquidityProviderAddress
) external initializer {
require(_owner != address(0), "Zero address");
require(_tokenAddress.isContract(), "Not a contract address");
Ownable.initialize(msg.sender);
ReentrancyGuard.initialize();
token = IERC20Mintable(_tokenAddress);
tokenReward = IERC20Mintable(_tokenReward);
setLiquidityProviderAddress(_liquidityProviderAddress);
Ownable.transferOwnership(_owner);
}
/**
* @dev Sets the address for the Liquidity Providers reward.
* Can only be called by owner.
* @param _address The new address.
*/
function setLiquidityProviderAddress(address _address) public onlyOwner {
require(_address != address(0), "Zero address");
require(_address != address(this), "Wrong address");
AddressParam memory param = liquidityProviderAddressParam;
if (param.timestamp == 0) {
param.oldValue = _address;
} else if (_paramUpdateDelayElapsed(param.timestamp)) {
param.oldValue = param.newValue;
}
param.newValue = _address;
param.timestamp = _now();
liquidityProviderAddressParam = param;
emit LiquidityProviderAddressSet(_address, msg.sender);
}
/**
* @return Returns true if param update delay elapsed.
*/
function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) {
return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY);
}
/**
* @dev This method is used to deposit tokens to the deposit opened before.
* It calls the internal "_deposit" method and transfers tokens from sender to contract.
* Sender must approve tokens first.
*
* Instead this, user can use the simple "transferFrom" method of OVR token contract to make a deposit.
*
* @param _depositId User's unique deposit ID.
* @param _amount The amount to deposit.
*/
function deposit(uint256 _depositId, uint256 _amount)
public
validDepositId(_depositId)
isNotLocked
isNotPaused
isNotPausedDepositAndLockupExtensions
{
require(_amount > 0, "Amount should be more than 0");
_deposit(msg.sender, _depositId, _amount);
_setLocked(true);
require(token.transferFrom(msg.sender, address(this), _amount), "Transfer failed");
_setLocked(false);
}
/**
* @param _sender The address of the sender.
* @param _depositId User's deposit ID.
* @param _amount The amount to deposit.
*/
function _deposit(
address _sender,
uint256 _depositId,
uint256 _amount
) internal nonReentrant {
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance = calcRewards(_sender, _depositId);
uint256 timestamp = _now();
balances[_sender][_depositId] = _amount.add(finalBalance);
depositDates[_sender][_depositId] = _now();
emit Deposited(_sender, _depositId, _amount, currentBalance, timestamp);
}
/**
* @dev This method is used to withdraw rewards and balance.
* It calls the internal "_withdrawAll" method.
* @param _depositId User's unique deposit ID
*/
function withdrawAll(uint256 _depositId) external balanceExists(_depositId) validDepositId(_depositId) isNotPaused {
require(isLockupPeriodExpired(_depositId), "Too early, Lockup period");
_withdrawAll(msg.sender, _depositId);
}
function _withdrawAll(address _sender, uint256 _depositId)
internal
balanceExists(_depositId)
validDepositId(_depositId)
nonReentrant
{
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance = calcRewards(_sender, _depositId);
require(finalBalance > 0, "Nothing to withdraw");
balances[_sender][_depositId] = 0;
_setLocked(true);
require(tokenReward.transfer(_sender, finalBalance), "Liquidity pool transfer failed");
_setLocked(false);
emit WithdrawnAll(_sender, _depositId, finalBalance, currentBalance, _now());
}
/**
* This method is used to extend lockup. It is available if your lockup period is expired and if depositId != 1
* It calls the internal "_extendLockup" method.
* @param _depositId User's unique deposit ID
*/
function extendLockup(uint256 _depositId)
external
balanceExists(_depositId)
validDepositId(_depositId)
isNotPaused
isNotPausedDepositAndLockupExtensions
{
require(_depositId != 1, "No lockup is set up");
_extendLockup(msg.sender, _depositId);
}
function _extendLockup(address _sender, uint256 _depositId) internal nonReentrant {
uint256 timestamp = _now();
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance = calcRewards(_sender, _depositId);
balances[_sender][_depositId] = finalBalance;
depositDates[_sender][_depositId] = timestamp;
emit ExtendedLockup(_sender, _depositId, currentBalance, finalBalance, timestamp);
}
function isLockupPeriodExpired(uint256 _depositId) public view validDepositId(_depositId) returns (bool) {
uint256 lockPeriod;
if (_depositId == 1) {
lockPeriod = 0;
} else if (_depositId == 2) {
lockPeriod = MONTH * 3; // 3 months
} else if (_depositId == 3) {
lockPeriod = MONTH * 6; // 6 months
} else if (_depositId == 4) {
lockPeriod = MONTH * 9; // 9 months
} else if (_depositId == 5) {
lockPeriod = MONTH * 12; // 12 months
}
if (_now() > depositDates[msg.sender][_depositId].add(lockPeriod)) {
return true;
} else {
return false;
}
}
function pow(int128 _x, uint256 _n) public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt(1);
while (_n > 0) {
if (_n % 2 == 1) {
r = ABDKMath64x64.mul(r, _x);
_n -= 1;
} else {
_x = ABDKMath64x64.mul(_x, _x);
_n /= 2;
}
}
}
/**
* This method is calcuate final compouded capital.
* @param _principal User's balance
* @param _ratio Interest rate
* @param _n Periods is timestamp
* @return finalBalance The final compounded capital
*
* A = C ( 1 + rate )^t
*/
function compound(
uint256 _principal,
uint256 _ratio,
uint256 _n
) public view returns (uint256) {
uint256 daysCount = _n.div(DAY);
return
ABDKMath64x64.mulu(
pow(ABDKMath64x64.add(ABDKMath64x64.fromUInt(1), ABDKMath64x64.divu(_ratio, 10**18)), daysCount),
_principal
);
}
/**
* This moethod is used to calculate final compounded balance and is based on deposit duration and deposit id.
* Each deposit mode is characterized by the lockup period and interest rate.
* At the expiration of the lockup period the final compounded capital
* will use minimum interest rate.
*
* This function can be called at any time to get the current total reward.
* @param _sender Sender Address.
* @param _depositId The depositId
* @return finalBalance The final compounded capital
*/
function calcRewards(address _sender, uint256 _depositId) public view validDepositId(_depositId) returns (uint256) {
uint256 timePassed = _now().sub(depositDates[_sender][_depositId]);
uint256 currentBalance = getCurrentBalance(_depositId, _sender);
uint256 finalBalance;
uint256 ratio;
uint256 lockPeriod;
if (_depositId == 1) {
ratio = 100000000000000; // APY 3.7% InterestRate = 0.01
lockPeriod = 0;
} else if (_depositId == 2) {
ratio = 300000000000000; // APY 11.6% InterestRate = 0.03
lockPeriod = MONTH * 3; // 3 months
} else if (_depositId == 3) {
ratio = 400000000000000; // APY 15.7% InterestRate = 0.04
lockPeriod = MONTH * 6; // 6 months
} else if (_depositId == 4) {
ratio = 600000000000000; // APY 25.5% InterestRate = 0.06
lockPeriod = MONTH * 9; // 9 months
} else if (_depositId == 5) {
ratio = 800000000000000; // APY 33.9% InterestRate = 0.08
lockPeriod = YEAR; // 12 months
}
// You can't have earnings without balance
if (currentBalance == 0) {
return finalBalance = 0;
}
// No lockup
if (_depositId == 1) {
finalBalance = compound(currentBalance, ratio, timePassed);
return finalBalance;
}
// If you have an uncovered period from lockup, you still get rewards at the minimum rate
if (timePassed > lockPeriod) {
uint256 rewardsWithLockup = compound(currentBalance, ratio, lockPeriod).sub(currentBalance);
finalBalance = compound(rewardsWithLockup.add(currentBalance), 100000000000000, timePassed.sub(lockPeriod));
return finalBalance;
}
finalBalance = compound(currentBalance, ratio, timePassed);
return finalBalance;
}
function getCurrentBalance(uint256 _depositId, address _address) public view returns (uint256 addressBalance) {
addressBalance = balances[_address][_depositId];
}
/**
* @return Returns current liquidity providers reward address.
*/
function liquidityProviderAddress() public view returns (address) {
AddressParam memory param = liquidityProviderAddressParam;
return param.newValue;
}
/**
* @dev Sets lock to prevent reentrance.
*/
function _setLocked(bool _locked) internal {
locked = _locked;
}
function senderCurrentBalance() public view returns (uint256) {
return msg.sender.balance;
}
/**
* @return Returns current timestamp.
*/
function _now() internal view returns (uint256) {
// Note that the timestamp can have a 900-second error:
// https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md
// return now; // solium-disable-line security/no-block-members
return block.timestamp;
}
} | return Returns current liquidity providers reward address./ | function liquidityProviderAddress() public view returns (address) {
AddressParam memory param = liquidityProviderAddressParam;
return param.newValue;
}
| 6,261,591 |
./full_match/1/0xE344921ec4A8a9E3B41F7BCD678F4bcB77922bFB/sources/contracts/OnChainBunnies.sol | Creates the tokenURI which contains the name, description, generated SVG image and token traits/ | function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "Non-Existing");
string memory svgData = renderTokenById(tokenId);
string memory traits = getTraits(tokenId);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',
name(),
" ",
Strings.toString(tokenId),
'", "description": "',
"ocb"
'", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(svgData)),
bytes(traits).length == 0 ? '"' : '", "attributes": ',
traits,
"}"
)
)
)
);
return string(abi.encodePacked("data:application/json;base64,", json));
}
| 2,959,982 |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @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 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed integers. Reverts on
/// division by zero. The result is rounded towards zero.
/// Counterpart to Solidity's `/` operator. 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 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @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 (ReserveData memory);
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @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);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
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);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
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, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @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
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @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
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @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
*/
function approve(address spender, uint256 amount) external;
/**
* @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 remaining The number of tokens allowed to be spent
*/
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);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
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) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
} | Returns the next settle time for the nToken which is 1 quarter away | function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
| 12,680 |
./full_match/1/0xc0163F657b48Cd5058b256334c002e4D02Fdc3C4/sources/EsusuAdapter.sol | set _isActive to false Send yDai shares to the new contract and halt operations of this contract | function DepricateContract(
address newEsusuAdapterContract,
string calldata reason
) external onlyOwner {
_isActive = false;
uint256 yDaiSharesBalance = _yDai.balanceOf(address(this));
_yDai.safeTransfer(newEsusuAdapterContract, yDaiSharesBalance);
DepricateContractEvent(now, owner, reason, yDaiSharesBalance);
}
| 8,304,127 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./libs/SafeBEP20.sol";
import "./libs/BEP20.sol";
// MarsToken with Governance.
contract MarsToken is BEP20('Mars', 'XMS') {
using SafeMath for uint256;
address public minter;
constructor () public {
uint256 initAmout = 13000000;
_mint(msg.sender, initAmout.mul(10**decimals()));
minter = msg.sender;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public {
require(_to != address(0), "zero address");
require(msg.sender == minter, "not minter");
_mint(_to, _amount);
}
function setMinter(address _minter) public onlyOwner {
require(_minter != address(0), "zero address");
minter = _minter;
}
} | Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). | function mint(address _to, uint256 _amount) public {
require(_to != address(0), "zero address");
require(msg.sender == minter, "not minter");
_mint(_to, _amount);
}
| 5,353,001 |
./partial_match/1/0x891696CCa87aa2f175124b412198c23D54680E31/sources/NFTWinner.sol | Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist./ | function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId].value;
}
| 3,585,520 |
contract Multiowned {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// EVENT
// this contract only has five types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner, bytes32 operation);
event OwnerAdded(address newOwner, bytes32 operation);
event OwnerRemoved(address oldOwner, bytes32 operation);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement, bytes32 operation);
event Operation(bytes32 operation);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyOwner {
if (isOwner(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlyManyOwners(bytes32 _operation) {
Operation(_operation);
if (confirmAndCheck(_operation))
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlyManyOwners" transactions
// as well as the selection of addresses capable of confirming them.
function Multiowned() public{
m_numOwners = 1;
m_owners[1] = uint(msg.sender);
m_ownerIndex[uint(msg.sender)] = 1;
m_required = 1;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
var pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) onlyManyOwners(keccak256(msg.data)) external {
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
OwnerChanged(_from, _to, keccak256(msg.data));
}
function addOwner(address _owner) onlyManyOwners(keccak256(msg.data)) external {
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
OwnerAdded(_owner,keccak256(msg.data));
}
function removeOwner(address _owner) onlyManyOwners(keccak256(msg.data)) external {
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners - 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
OwnerRemoved(_owner,keccak256(msg.data));
}
function changeRequirement(uint _newRequired) onlyManyOwners(keccak256(msg.data)) external {
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired,keccak256(msg.data));
}
function isOwner(address _addr) view public returns (bool){
return m_ownerIndex[uint(_addr)] > 0;
}
//when the voting is complate, hasConfirmed return false
//if the voteing is ongoing, it returns whether _owner has voted the _operation
function hasConfirmed(bytes32 _operation, address _owner) view public returns (bool) {
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
// make sure they're an owner
if (ownerIndex == 0) return false;
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
var pending = m_pending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
}
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
if (m_pendingIndex[i] != 0)
delete m_pending[m_pendingIndex[i]];
delete m_pendingIndex;
}
// FIELDS
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners
uint[256] m_owners;
uint constant c_maxOwners = 250;
// index on the list of owners to allow reverse lookup
mapping(uint => uint) m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
}
contract Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
uint256 constant MAX_UINT256 = 2**256 - 1;
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract UGCoin is Multiowned, StandardToken {
event Freeze(address from, uint value);
event Defreeze(address ownerAddr, address userAddr, uint256 amount);
event ReturnToOwner(address ownerAddr, uint amount);
event Destroy(address from, uint value);
function UGCoin() public Multiowned(){
balances[msg.sender] = initialAmount; // Give the creator all initial balances is defined in StandardToken.sol
totalSupply = initialAmount; // Update total supply, totalSupply is defined in Tocken.sol
}
function() public {
}
/* transfer UGC to DAS */
function freeze(uint256 _amount) external returns (bool success){
require(balances[msg.sender] >= _amount);
coinPool += _amount;
balances[msg.sender] -= _amount;
Freeze(msg.sender, _amount);
return true;
}
/* transfer UGC from DAS */
function defreeze(address _userAddr, uint256 _amount) onlyOwner external returns (bool success){
require(balances[msg.sender] >= _amount); //msg.sender is a owner
require(coinPool >= _amount);
balances[_userAddr] += _amount;
balances[msg.sender] -= _amount;
ownersLoan[msg.sender] += _amount;
Defreeze(msg.sender, _userAddr, _amount);
return true;
}
function returnToOwner(address _ownerAddr, uint256 _amount) onlyManyOwners(keccak256(msg.data)) external returns (bool success){
require(coinPool >= _amount);
require(isOwner(_ownerAddr));
require(ownersLoan[_ownerAddr] >= _amount);
balances[_ownerAddr] += _amount;
coinPool -= _amount;
ownersLoan[_ownerAddr] -= _amount;
ReturnToOwner(_ownerAddr, _amount);
return true;
}
function destroy(uint256 _amount) external returns (bool success){
require(balances[msg.sender] >= _amount);
balances[msg.sender] -= _amount;
totalSupply -= _amount;
Destroy(msg.sender, _amount);
return true;
}
function getOwnersLoan(address _ownerAddr) view public returns (uint256){
return ownersLoan[_ownerAddr];
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified.
//This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed when one does this that the call *should* succeed, otherwise one would use vanilla approve instead.
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
string public name = "UG Coin";
uint8 public decimals = 18;
string public symbol = "UGC";
string public version = "v0.1";
uint256 public initialAmount = (10 ** 9) * (10 ** 18);
uint256 public coinPool = 0; // coinPool is a pool for freezing UGC
mapping (address => uint256) ownersLoan; // record the amount of UGC paid by oweners for freezing UGC
} | when the voting is complate, hasConfirmed return falseif the voteing is ongoing, it returns whether _owner has voted the _operation make sure they're an owner determine the bit to set for this owner. | function hasConfirmed(bytes32 _operation, address _owner) view public returns (bool) {
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return false;
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
}
| 13,041,480 |
./full_match/1/0x81E11c4701C5189b0122ef42DaF1fF3d453D968E/sources/contracts/wallet/base/ModuleManager.sol | Allows to remove a module from the whitelist. This can only be done via a Safe transaction. Disables the module `module` for the Safe. prevModule Module that pointed to the module to be removed in the linked list module Module to be removed. Validate module address and check that it corresponds to module index. | function disableModule(
address prevModule,
address module
) public authorized {
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
require(modules[prevModule] == module, "GS103");
modules[prevModule] = modules[module];
modules[module] = address(0);
emit DisabledModule(module);
}
| 8,301,812 |
pragma solidity 0.4.19;
import "./utils/Secured.sol";
contract Store is Secured
{
/**** Storage Types *******/
mapping(bytes32 => uint256) private uintStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**** Get Methods ***********/
/// @param _key The key for the record
function getAddress(bytes32 _key) external view returns (address)
{
return addressStorage[_key];
}
/// @param _key The key for the record
function getUint(bytes32 _key) external view returns (uint)
{
return uintStorage[_key];
}
/// @param _key The key for the record
function getString(bytes32 _key) external view returns (string)
{
return stringStorage[_key];
}
/// @param _key The key for the record
function getBytes(bytes32 _key) external view returns (bytes)
{
return bytesStorage[_key];
}
/// @param _key The key for the record
function getBool(bytes32 _key) external view returns (bool)
{
return boolStorage[_key];
}
/// @param _key The key for the record
function getInt(bytes32 _key) external view returns (int)
{
return intStorage[_key];
}
/**** Set Methods ***********/
/// @param _key The key for the record
function setAddress(bytes32 _key, address _value) onlyAuthorized external
{
addressStorage[_key] = _value;
}
/// @param _key The key for the record
function setUint(bytes32 _key, uint _value) onlyAuthorized external
{
uintStorage[_key] = _value;
}
/// @param _key The key for the record
function setString(bytes32 _key, string _value) onlyAuthorized external
{
stringStorage[_key] = _value;
}
/// @param _key The key for the record
function setBytes(bytes32 _key, bytes _value) onlyAuthorized external
{
bytesStorage[_key] = _value;
}
/// @param _key The key for the record
function setBool(bytes32 _key, bool _value) onlyAuthorized external
{
boolStorage[_key] = _value;
}
/// @param _key The key for the record
function setInt(bytes32 _key, int _value) onlyAuthorized external
{
intStorage[_key] = _value;
}
/**** Delete Methods ***********/
/// @param _key The key for the record
function deleteAddress(bytes32 _key) onlyAuthorized external
{
delete addressStorage[_key];
}
/// @param _key The key for the record
function deleteUint(bytes32 _key) onlyAuthorized external
{
delete uintStorage[_key];
}
/// @param _key The key for the record
function deleteString(bytes32 _key) onlyAuthorized external
{
delete stringStorage[_key];
}
/// @param _key The key for the record
function deleteBytes(bytes32 _key) onlyAuthorized external
{
delete bytesStorage[_key];
}
/// @param _key The key for the record
function deleteBool(bytes32 _key) onlyAuthorized external
{
delete boolStorage[_key];
}
/// @param _key The key for the record
function deleteInt(bytes32 _key) onlyAuthorized external
{
delete intStorage[_key];
}
} | _key The key for the record | function setInt(bytes32 _key, int _value) onlyAuthorized external
{
intStorage[_key] = _value;
}
| 12,567,421 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Lib_PredeployAddresses } from "../libraries/Lib_PredeployAddresses.sol";
import { L1Block } from "../L2/L1Block.sol";
/**
* @custom:proxied
* @custom:predeploy 0x420000000000000000000000000000000000000F
* @title GasPriceOracle
* @notice This contract maintains the variables responsible for computing the L1 portion of the
* total fee charged on L2. The values stored in the contract are looked up as part of the
* L2 state transition function and used to compute the total fee paid by the user. The
* contract exposes an API that is useful for knowing how large the L1 portion of their
* transaction fee will be.
*/
contract GasPriceOracle is Ownable {
/**
* @custom:legacy
* @notice Spacer for backwards compatibility.
*/
uint256 internal spacer0;
/**
* @custom:legacy
* @notice Spacer for backwards compatibility.
*/
uint256 internal spacer1;
/**
* @notice Constant L1 gas overhead per transaction.
*/
uint256 public overhead;
/**
* @notice Dynamic L1 gas overhead per transaction.
*/
uint256 public scalar;
/**
* @notice Number of decimals used in the scalar.
*/
uint256 public decimals;
/**
* @param _owner Address that will initially own this contract.
*/
constructor(address _owner) Ownable() {
transferOwnership(_owner);
}
/**
* @notice Emitted when the overhead value is updated.
*/
event OverheadUpdated(uint256 overhead);
/**
* @notice Emitted when the scalar value is updated.
*/
event ScalarUpdated(uint256 scalar);
/**
* @notice Emitted when the decimals value is updated.
*/
event DecimalsUpdated(uint256 decimals);
/**
* @notice Retrieves the current gas price (base fee).
*
* @return Current L2 gas price (base fee).
*/
function gasPrice() public returns (uint256) {
return block.basefee;
}
/**
* @notice Retrieves the current base fee.
*
* @return Current L2 base fee.
*/
function baseFee() public returns (uint256) {
return block.basefee;
}
/**
* @notice Retrieves the latest known L1 base fee.
*
* @return Latest known L1 base fee.
*/
function l1BaseFee() public view returns (uint256) {
return L1Block(Lib_PredeployAddresses.L1_BLOCK_ATTRIBUTES).basefee();
}
/**
* @notice Allows the owner to modify the overhead.
*
* @param _overhead New overhead value.
*/
function setOverhead(uint256 _overhead) external onlyOwner {
overhead = _overhead;
emit OverheadUpdated(_overhead);
}
/**
* @notice Allows the owner to modify the scalar.
*
* @param _scalar New scalar value.
*/
function setScalar(uint256 _scalar) external onlyOwner {
scalar = _scalar;
emit ScalarUpdated(_scalar);
}
/**
* @notice Allows the owner to modify the decimals.
*
* @param _decimals New decimals value.
*/
function setDecimals(uint256 _decimals) external onlyOwner {
decimals = _decimals;
emit DecimalsUpdated(_decimals);
}
/**
* @notice Computes the L1 portion of the fee based on the size of the rlp encoded input
* transaction, the current L1 base fee, and the various dynamic parameters.
*
* @param _data Unsigned fully RLP-encoded transaction to get the L1 fee for.
*
* @return L1 fee that should be paid for the tx
*/
function getL1Fee(bytes memory _data) external view returns (uint256) {
uint256 l1GasUsed = getL1GasUsed(_data);
uint256 l1Fee = l1GasUsed * l1BaseFee();
uint256 divisor = 10**decimals;
uint256 unscaled = l1Fee * scalar;
uint256 scaled = unscaled / divisor;
return scaled;
}
/**
* @notice Computes the amount of L1 gas used for a transaction. Adds the overhead which
* represents the per-transaction gas overhead of posting the transaction and state
* roots to L1. Adds 68 bytes of padding to account for the fact that the input does
* not have a signature.
*
* @param _data Unsigned fully RLP-encoded transaction to get the L1 gas for.
*
* @return Amount of L1 gas used to publish the transaction.
*/
function getL1GasUsed(bytes memory _data) public view returns (uint256) {
uint256 total = 0;
uint256 length = _data.length;
for (uint256 i = 0; i < length; i++) {
if (_data[i] == 0) {
total += 4;
} else {
total += 16;
}
}
uint256 unsigned = total + overhead;
return unsigned + (68 * 16);
}
}
| Retrieves the latest known L1 base fee. return Latest known L1 base fee./ | function l1BaseFee() public view returns (uint256) {
return L1Block(Lib_PredeployAddresses.L1_BLOCK_ATTRIBUTES).basefee();
}
| 12,904,083 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "sol-temple/src/tokens/ERC721.sol";
import "sol-temple/src/utils/Auth.sol";
import "sol-temple/src/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* @title Ape Runners
* @author naomsa <https://twitter.com/naomsa666>
*/
contract ApeRunners is Auth, Pausable, ERC721("Ape Runners", "AR") {
using Strings for uint256;
using MerkleProof for bytes32[];
/// @notice Max supply.
uint256 public constant MAX_SUPPLY = 5000;
/// @notice Max amount per claim (public sale).
uint256 public constant MAX_PER_TX = 10;
/// @notice Claim price.
uint256 public constant PRICE = 0.04 ether;
/// @notice 0 = CLOSED, 1 = WHITELIST, 2 = PUBLIC.
uint256 public saleState;
/// @notice Metadata base URI.
string public baseURI;
/// @notice Metadata URI extension.
string public baseExtension;
/// @notice Unrevealed metadata URI.
string public unrevealedURI;
/// @notice Whitelist merkle root.
bytes32 public merkleRoot;
/// @notice Whitelist mints per address.
mapping(address => uint256) public whitelistMinted;
/// @notice OpenSea proxy registry.
address public opensea;
/// @notice LooksRare marketplace transfer manager.
address public looksrare;
/// @notice Check if marketplaces pre-approve is enabled.
bool public marketplacesApproved = true;
constructor(
string memory unrevealedURI_,
bytes32 merkleRoot_,
address opensea_,
address looksrare_
) {
unrevealedURI = unrevealedURI_;
merkleRoot = merkleRoot_;
opensea = opensea_;
looksrare = looksrare_;
for (uint256 i = 0; i < 50; i++) _safeMint(msg.sender, i);
}
/// @notice Claim one or more tokens.
function claim(uint256 amount_) external payable {
uint256 supply = totalSupply();
require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded");
if (msg.sender != owner()) {
require(saleState == 2, "Public sale is not open");
require(amount_ > 0 && amount_ <= MAX_PER_TX, "Invalid claim amount");
require(msg.value == PRICE * amount_, "Invalid ether amount");
}
for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++);
}
/// @notice Claim one or more tokens for whitelisted user.
function claimWhitelist(uint256 amount_, bytes32[] memory proof_)
external
payable
{
uint256 supply = totalSupply();
require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded");
if (msg.sender != owner()) {
require(saleState == 1, "Whitelist sale is not open");
require(
amount_ > 0 && amount_ + whitelistMinted[msg.sender] <= MAX_PER_TX,
"Invalid claim amount"
);
require(msg.value == PRICE * amount_, "Invalid ether amount");
require(isWhitelisted(msg.sender, proof_), "Invalid proof");
}
whitelistMinted[msg.sender] += amount_;
for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++);
}
/// @notice Retrieve if `user_` is whitelisted based on his `proof_`.
function isWhitelisted(address user_, bytes32[] memory proof_)
public
view
returns (bool)
{
bytes32 leaf = keccak256(abi.encodePacked(user_));
return proof_.verify(merkleRoot, leaf);
}
/**
* @notice See {IERC721-tokenURI}.
* @dev In order to make a metadata reveal, there must be an unrevealedURI string, which
* gets set on the constructor and, for optimization purposes, when the owner() sets a new
* baseURI, the unrevealedURI gets deleted, saving gas and triggering a reveal.
*/
function tokenURI(uint256 tokenId_)
public
view
override
returns (string memory)
{
if (bytes(unrevealedURI).length > 0) return unrevealedURI;
return
string(abi.encodePacked(baseURI, tokenId_.toString(), baseExtension));
}
/// @notice Set baseURI to `baseURI_`, baseExtension to `baseExtension_` and deletes unrevealedURI, triggering a reveal.
function setBaseURI(string memory baseURI_, string memory baseExtension_)
external
onlyAuthorized
{
baseURI = baseURI_;
baseExtension = baseExtension_;
delete unrevealedURI;
}
/// @notice Set unrevealedURI to `unrevealedURI_`.
function setUnrevealedURI(string memory unrevealedURI_)
external
onlyAuthorized
{
unrevealedURI = unrevealedURI_;
}
/// @notice Set unrevealedURI to `unrevealedURI_`.
function setSaleState(uint256 saleState_) external onlyAuthorized {
saleState = saleState_;
}
/// @notice Set merkleRoot to `merkleRoot_`.
function setMerkleRoot(bytes32 merkleRoot_) external onlyAuthorized {
merkleRoot = merkleRoot_;
}
/// @notice Set opensea to `opensea_`.
function setOpensea(address opensea_) external onlyAuthorized {
opensea = opensea_;
}
/// @notice Set looksrare to `looksrare_`.
function setLooksrare(address looksrare_) external onlyAuthorized {
looksrare = looksrare_;
}
/// @notice Toggle pre-approve feature state for sender.
function toggleMarketplacesApproved() external onlyAuthorized {
marketplacesApproved = !marketplacesApproved;
}
/// @notice Toggle paused state.
function togglePaused() external onlyAuthorized {
_togglePaused();
}
/**
* @notice Withdraw `amount_` of ether to msg.sender.
* @dev Combined with the Auth util, this function can be called by
* anyone with the authorization from the owner, so a team member can
* get his shares with a permissioned call and exact data.
*/
function withdraw(uint256 amount_) external onlyAuthorized {
payable(msg.sender).transfer(amount_);
}
/// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales.
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
if (!marketplacesApproved) return super.isApprovedForAll(owner, operator);
return
operator == OpenSeaProxyRegistry(opensea).proxies(owner) ||
operator == looksrare ||
super.isApprovedForAll(owner, operator);
}
/// @dev Edited in order to block transfers while paused unless msg.sender is the owner().
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
require(
msg.sender == owner() || paused() == false,
"Pausable: contract paused"
);
super._beforeTokenTransfer(from, to, tokenId);
}
}
contract OpenSeaProxyRegistry {
mapping(address => address) public proxies;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0 <0.9.0;
/**
* @title ERC721
* @author naomsa <https://twitter.com/naomsa666>
* @notice A complete ERC721 implementation including metadata and enumerable
* functions. Completely gas optimized and extensible.
*/
abstract contract ERC721 {
/* _ _ */
/* ( )_ ( )_ */
/* ___ | ,_) _ _ | ,_) __ */
/* /',__)| | /'_` )| | /'__`\ */
/* \__, \| |_ ( (_| || |_ ( ___/ */
/* (____/`\__)`\__,_)`\__)`\____) */
/// @dev This emits when ownership of any NFT changes by any mechanism.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice See {IERC721Metadata-name}.
string public name;
/// @notice See {IERC721Metadata-symbol}.
string public symbol;
/// @notice Array of all owners.
address[] private _owners;
/// @notice Mapping of all balances.
mapping(address => uint256) private _balanceOf;
/// @notice Mapping from token ID to approved address.
mapping(uint256 => address) private _tokenApprovals;
/// @notice Mapping of approvals between owner and operator.
mapping(address => mapping(address => bool)) private _isApprovedForAll;
/* _ */
/* (_ ) _ */
/* | | _ __ (_) ___ */
/* | | /'_`\ /'_ `\| | /'___) */
/* | | ( (_) )( (_) || |( (___ */
/* (___)`\___/'`\__ |(_)`\____) */
/* ( )_) | */
/* \___/' */
constructor(string memory name_, string memory symbol_) {
name = name_;
symbol = symbol_;
}
/// @notice See {IERC721-balanceOf}.
function balanceOf(address owner) public view virtual returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balanceOf[owner];
}
/// @notice See {IERC721-ownerOf}.
function ownerOf(uint256 tokenId) public view virtual returns (address) {
require(_exists(tokenId), "ERC721: query for nonexistent token");
address owner = _owners[tokenId];
return owner;
}
/// @notice See {IERC721Metadata-tokenURI}.
function tokenURI(uint256) public view virtual returns (string memory);
/// @notice See {IERC721-approve}.
function approve(address to, uint256 tokenId) public virtual {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || _isApprovedForAll[owner][msg.sender],
"ERC721: caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/// @notice See {IERC721-getApproved}.
function getApproved(uint256 tokenId) public view virtual returns (address) {
require(_exists(tokenId), "ERC721: query for nonexistent token");
return _tokenApprovals[tokenId];
}
/// @notice See {IERC721-setApprovalForAll}.
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(msg.sender, operator, approved);
}
/// @notice See {IERC721-isApprovedForAll}
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _isApprovedForAll[owner][operator];
}
/// @notice See {IERC721-transferFrom}.
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/// @notice See {IERC721-safeTransferFrom}.
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual {
safeTransferFrom(from, to, tokenId, "");
}
/// @notice See {IERC721-safeTransferFrom}.
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data_
) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, data_);
}
/// @notice See {IERC721Enumerable.tokenOfOwnerByIndex}.
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId) {
require(index < balanceOf(owner), "ERC721Enumerable: Index out of bounds");
uint256 count;
for (uint256 i; i < _owners.length; ++i) {
if (owner == _owners[i]) {
if (count == index) return i;
else count++;
}
}
revert("ERC721Enumerable: Index out of bounds");
}
/// @notice See {IERC721Enumerable.totalSupply}.
function totalSupply() public view virtual returns (uint256) {
return _owners.length;
}
/// @notice See {IERC721Enumerable.tokenByIndex}.
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
require(index < _owners.length, "ERC721Enumerable: Index out of bounds");
return index;
}
/// @notice Returns a list of all token Ids owned by `owner`.
function tokensOfOwner(address owner) public view returns (uint256[] memory) {
uint256 balance = balanceOf(owner);
uint256[] memory ids = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
ids[i] = tokenOfOwnerByIndex(owner, i);
}
return ids;
}
/* _ _ */
/* _ ( )_ (_ ) */
/* (_) ___ | ,_) __ _ __ ___ _ _ | | */
/* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */
/* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */
/* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */
/**
* @notice 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);
_checkOnERC721Received(from, to, tokenId, data_);
}
/**
* @notice Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
/**
* @notice 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: query for nonexistent token");
address owner = _owners[tokenId];
return (spender == owner || getApproved(tokenId) == spender || _isApprovedForAll[owner][spender]);
}
/**
* @notice 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, "");
}
/**
* @notice Same as {_safeMint}, but 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);
_checkOnERC721Received(address(0), to, tokenId, data_);
}
/**
* @notice Mints `tokenId` and transfers it to `to`.
*
* Requirements:
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
unchecked {
_balanceOf[to]++;
}
emit Transfer(address(0), to, tokenId);
}
/**
* @notice 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 = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
delete _owners[tokenId];
_balanceOf[owner]--;
emit Transfer(owner, address(0), tokenId);
}
/**
* @notice Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(_owners[tokenId] == from, "ERC721: transfer of token that is not own");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
unchecked {
_balanceOf[from]--;
_balanceOf[to]++;
}
emit Transfer(from, to, tokenId);
}
/**
* @notice Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(_owners[tokenId], to, tokenId);
}
/**
* @notice Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_isApprovedForAll[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @notice 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
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (bytes4 returned) {
require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation");
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: safe transfer to non ERC721Receiver implementation");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/**
* @notice 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.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/* ___ _ _ _ _ __ _ __ */
/* /',__)( ) ( )( '_`\ /'__`\( '__) */
/* \__, \| (_) || (_) )( ___/| | */
/* (____/`\___/'| ,__/'`\____)(_) */
/* | | */
/* (_) */
/// @notice See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return
interfaceId == 0x80ac58cd || // ERC721
interfaceId == 0x5b5e139f || // ERC721Metadata
interfaceId == 0x780e9d63 || // ERC721Enumerable
interfaceId == 0x01ffc9a7; // ERC165
}
}
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) external returns (bytes4);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0 <0.9.0;
/**
* @title Auth
* @author naomsa <https://twitter.com/naomsa666>
* @notice Authing system where the `owner` can authorize function calls
* to other addresses as well as control the contract by his own.
*/
abstract contract Auth {
/* _ _ */
/* ( )_ ( )_ */
/* ___ | ,_) _ _ | ,_) __ */
/* /',__)| | /'_` )| | /'__`\ */
/* \__, \| |_ ( (_| || |_ ( ___/ */
/* (____/`\__)`\__,_)`\__)`\____) */
/// @notice Emited when the ownership is transfered.
event OwnershipTransfered(address indexed from, address indexed to);
/// @notice Emited a new call with `data` is authorized to `to`.
event AuthorizationGranted(address indexed to, bytes data);
/// @notice Emited a new call with `data` is forbidden to `to`.
event AuthorizationForbidden(address indexed to, bytes data);
/// @notice Contract's owner address.
address private _owner;
/// @notice A mapping to retrieve if a call data was authed and is valid for the address.
mapping(address => mapping(bytes => bool)) private _isAuthorized;
/**
* @notice A modifier that requires the user to be the owner or authorization to call.
* After the call, the user loses it's authorization if he's not the owner.
*/
modifier onlyAuthorized() {
require(isAuthorized(msg.sender, msg.data), "Auth: sender is not the owner or authorized to call");
_;
if (msg.sender != _owner) _isAuthorized[msg.sender][msg.data] = false;
}
/// @notice A simple modifier just to check whether the sender is the owner.
modifier onlyOwner() {
require(msg.sender == _owner, "Auth: sender is not the owner");
_;
}
/* _ */
/* (_ ) _ */
/* | | _ __ (_) ___ */
/* | | /'_`\ /'_ `\| | /'___) */
/* | | ( (_) )( (_) || |( (___ */
/* (___)`\___/'`\__ |(_)`\____) */
/* ( )_) | */
/* \___/' */
constructor() {
_transferOwnership(msg.sender);
}
/// @notice Returns the current contract owner.
function owner() public view returns (address) {
return _owner;
}
/// @notice Retrieves whether `user_` is authorized to call with `data_`.
function isAuthorized(address user_, bytes memory data_) public view returns (bool) {
return user_ == _owner || _isAuthorized[user_][data_];
}
/// @notice Set the owner address to `owner_`.
function transferOwnership(address owner_) public onlyOwner {
require(_owner != owner_, "Auth: transfering ownership to current owner");
_transferOwnership(owner_);
}
/// @notice Set the owner address to `owner_`. Does not require anything
function _transferOwnership(address owner_) internal {
address oldOwner = _owner;
_owner = owner_;
emit OwnershipTransfered(oldOwner, owner_);
}
/// @notice Authorize a call with `data_` to the address `to_`.
function auth(address to_, bytes memory data_) public onlyOwner {
require(to_ != _owner, "Auth: authorizing call to the owner");
require(!_isAuthorized[to_][data_], "Auth: authorized calls cannot be authed");
_isAuthorized[to_][data_] = true;
emit AuthorizationGranted(to_, data_);
}
/// @notice Authorize a call with `data_` to the address `to_`.
function forbid(address to_, bytes memory data_) public onlyOwner {
require(_isAuthorized[to_][data_], "Auth: unauthorized calls cannot be forbidden");
delete _isAuthorized[to_][data_];
emit AuthorizationForbidden(to_, data_);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0 <0.9.0;
/**
* @title Pausable
* @author naomsa <https://twitter.com/naomsa666>
* @notice Freeze your contract with a secure paused mechanism.
*/
abstract contract Pausable {
/* _ _ */
/* ( )_ ( )_ */
/* ___ | ,_) _ _ | ,_) __ */
/* /',__)| | /'_` )| | /'__`\ */
/* \__, \| |_ ( (_| || |_ ( ___/ */
/* (____/`\__)`\__,_)`\__)`\____) */
/// @notice Emited when the contract is paused.
event Paused(address indexed by);
/// @notice Emited when the contract is unpaused.
event Unpaused(address indexed by);
/// @notice Read-only pause state.
bool private _paused;
/// @notice A modifier to be used when the contract must be paused.
modifier onlyWhenPaused() {
require(_paused, "Pausable: contract not paused");
_;
}
/// @notice A modifier to be used when the contract must be unpaused.
modifier onlyWhenUnpaused() {
require(!_paused, "Pausable: contract paused");
_;
}
/* _ */
/* (_ ) _ */
/* | | _ __ (_) ___ */
/* | | /'_`\ /'_ `\| | /'___) */
/* | | ( (_) )( (_) || |( (___ */
/* (___)`\___/'`\__ |(_)`\____) */
/* ( )_) | */
/* \___/' */
/// @notice Retrieve contracts pause state.
function paused() public view returns (bool) {
return _paused;
}
/// @notice Inverts pause state. Declared internal so it can be combined with the Auth contract.
function _togglePaused() internal {
_paused = !_paused;
if (_paused) emit Unpaused(msg.sender);
else emit Paused(msg.sender);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
| Claim one or more tokens for whitelisted user. | function claimWhitelist(uint256 amount_, bytes32[] memory proof_)
external
payable
{
uint256 supply = totalSupply();
require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded");
if (msg.sender != owner()) {
require(saleState == 1, "Whitelist sale is not open");
require(
amount_ > 0 && amount_ + whitelistMinted[msg.sender] <= MAX_PER_TX,
"Invalid claim amount"
);
require(msg.value == PRICE * amount_, "Invalid ether amount");
require(isWhitelisted(msg.sender, proof_), "Invalid proof");
}
whitelistMinted[msg.sender] += amount_;
for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++);
}
| 5,470,632 |
./partial_match/42/0x3AC1B1628913631C03710de0cFbCFD7cea1A8b4a/sources/ICO.sol | low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. beneficiary Recipient of the token purchase/ nonReentrant payable view returns(uint256) calculate token amount to be created update state _processPurchase not working emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _forwardFunds(); | function buyTokens(address beneficiary) public nonReentrant payable{
uint256 weiAmount = 1;
_preValidatePurchase(beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
_weiRaised = _weiRaised.add(weiAmount);
_token.safeTransfer(beneficiary, tokens);
}
| 8,958,753 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
/// On Tupac's Soul
import "./ERC721A.sol";
import "./Payable.sol";
contract FoodlesClubToken is ERC721A, Payable {
using Strings for uint256;
// Token values incremented for gas efficiency
uint256 private maxSalePlusOne = 5001;
uint256 private constant MAX_RESERVED_PLUS_ONE = 51;
uint256 private constant MAX_FREE = 700;
uint256 private constant MAX_PER_TRANS_PLUS_ONE = 11;
uint256 private reserveClaimed = 0;
uint256 private freeClaimed = 0;
uint256 public tokenPrice = 0.03 ether;
bool public saleEnabled = false;
string public baseURI;
string public placeholderURI;
constructor() ERC721A("FoodlesClub", "FC", MAX_PER_TRANS_PLUS_ONE) Payable() {}
//
// Minting
//
/**
* Mint tokens
*/
function mint(uint256 numTokens, bool inclFreeMint) external payable {
require(msg.sender == tx.origin, "FoodlesClubToken: No bots");
require(saleEnabled, "FoodlesClubToken: Sale is not active");
require((totalSupply() + numTokens) < maxSalePlusOne, "FoodlesClubToken: Purchase exceeds available tokens");
if (inclFreeMint) {
// Free claim
require((numTokens - 1) < MAX_PER_TRANS_PLUS_ONE, "FoodlesClubToken: Can only mint 10 at a time");
require(freeClaimed < MAX_FREE, "FoodlesClubToken: Free claims exceeded");
require((tokenPrice * (numTokens - 1)) == msg.value, "FoodlesClubToken: Ether value sent is not correct");
freeClaimed++;
} else {
require(numTokens < MAX_PER_TRANS_PLUS_ONE, "FoodlesClubToken: Can only mint 10 at a time");
require((tokenPrice * numTokens) == msg.value, "FoodlesClubToken: Ether value sent is not correct");
}
_safeMint(msg.sender, numTokens);
}
/**
* Mints reserved tokens.
* @notice Max 10 per transaction.
*/
function mintReserved(uint256 numTokens, address mintTo) external onlyOwner {
require((totalSupply() + numTokens) < maxSalePlusOne, "FoodlesClubToken: Purchase exceeds available tokens");
require((reserveClaimed + numTokens) < MAX_RESERVED_PLUS_ONE, "FoodlesClubToken: Reservation exceeded");
reserveClaimed += numTokens;
_safeMint(mintTo, numTokens);
}
/**
* Toggle sale state
*/
function toggleSale() external onlyOwner {
saleEnabled = !saleEnabled;
}
/**
* Update token price
*/
function setTokenPrice(uint256 tokenPrice_) external onlyOwner {
tokenPrice = tokenPrice_;
}
/**
* Update maximum number of tokens for sale
*/
function setMaxSale(uint256 maxSale) external onlyOwner {
require(maxSale + 1 < maxSalePlusOne, "FoodlesClubToken: Can only reduce supply");
maxSalePlusOne = maxSale + 1;
}
/**
* Sets base URI
* @dev Only use this method after sell out as it will leak unminted token data.
*/
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* Sets placeholder URI
*/
function setPlaceholderURI(string memory _newPlaceHolderURI) external onlyOwner {
placeholderURI = _newPlaceHolderURI;
}
/**
* @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 uri = _baseURI();
return bytes(uri).length > 0 ? string(abi.encodePacked(uri, tokenId.toString(), ".json")) : placeholderURI;
}
/**
* @dev Return sale claim info.
* saleClaims[0]: maxSale (total available tokens)
* saleClaims[1]: totalSupply
* saleClaims[2]: reserveClaimed
* saleClaims[3]: freeClaimed
*/
function saleClaims() public view virtual returns (uint256[4] memory) {
return [maxSalePlusOne - 1, totalSupply(), reserveClaimed, freeClaimed];
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId) public view override(ERC721A, ERC2981) returns (bool) {
return ERC721A.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// Creators: locationtba.eth, 2pmflow.eth
pragma solidity >=0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @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("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
/// @title Payable
/// Manage payables
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./ERC2981.sol";
contract Payable is Ownable, ERC2981, ReentrancyGuard {
address private constant ADDR1 = 0x9CBcFb399312F8e8A8576140F226937261CC82bd; // The rest
address private constant ADDR2 = 0x3142829D0D9Ab30a1Dc56E3932949b4c10497E75; // 20
address private constant ADDR3 = 0xfeE840fFC2b70E5a4C280C852E30B13DB39CEd7a; // 20
address private constant ADDR4 = 0x235834A1E754996D825a92f2eA0bd39603d120Ec; // 5
constructor() {
_setRoyalties(ADDR1, 500); // 5% royalties
}
/**
* Set the royalties information
* @param recipient recipient of the royalties
* @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
*/
function setRoyalties(address recipient, uint256 value) external onlyOwner {
require(recipient != address(0), "zero address");
_setRoyalties(recipient, value);
}
/**
* Withdraw funds
*/
function withdraw() external nonReentrant() {
require(msg.sender == owner() || msg.sender == ADDR2, "Payable: Locked withdraw");
uint256 five = address(this).balance / 20;
Address.sendValue(payable(ADDR1), five * 11);
Address.sendValue(payable(ADDR2), five * 4);
Address.sendValue(payable(ADDR3), five * 4);
Address.sendValue(payable(ADDR4), five);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
contract ERC2981 is 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 IERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev 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.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol"; | Update maximum number of tokens for sale/ | function setMaxSale(uint256 maxSale) external onlyOwner {
require(maxSale + 1 < maxSalePlusOne, "FoodlesClubToken: Can only reduce supply");
maxSalePlusOne = maxSale + 1;
}
| 12,229,520 |
./full_match/4/0xBb3150D53953d616f895EAcea29C6E304E12461B/sources/browser/kp8r.sol | safely begin the governance transfer process. The new governance address, must accept the transfer. / | function transferGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governancePending = _governance;
}
| 659,396 |
pragma solidity 0.5.9;
/**
* https://rekt.fyi
*
* Mock the performance of your friend's ETH stack by sending them a REKT token, and add a bounty to it.
*
* REKT tokens are non-transferrable. Holders can only burn the token and collect the bounty once their
* ETH balance is m times higher or their ETH is worth m times more in USD than when they received the
* token, where m is a multiplier value set by users.
*
* copyright 2019 rekt.fyi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Libraries
*/
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
library DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
/**
* External Contracts
*/
contract Medianizer {
function peek() public view returns (bytes32, bool) {}
}
contract Dai {
function transferFrom(address src, address dst, uint wad) public returns (bool) {}
}
/**
* Contracts
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title https://rekt.fyi
* @notice Mock the performance of your friend's ETH stack by sending them a REKT token, and add a bounty to it.
*
* REKT tokens are non-transferrable. Holders can only burn the token and collect the bounty once their
* ETH balance is m times higher or their ETH is worth m times more in USD than when they received the
* token, where m is a multiplier value set by users.
*/
contract RektFyi is Ownable {
using DSMath for uint;
/**
* Storage
*/
struct Receiver {
uint walletBalance;
uint bountyETH;
uint bountyDAI;
uint timestamp;
uint etherPrice;
address payable sender;
}
struct Vault {
uint fee;
uint bountyETH;
uint bountySAI; // DAI bounty sent here before the switch to MCD
uint bountyDAI; // DAI bounty sent here after the switch to MCD
}
struct Pot {
uint ETH;
uint DAI;
}
mapping(address => Receiver) public receiver;
mapping(address => uint) public balance;
mapping(address => address[]) private recipients;
mapping(address => Pot) public unredeemedBounty;
mapping(address => Vault) public vault;
Pot public bountyPot = Pot(0,0);
uint public feePot = 0;
bool public shutdown = false;
uint public totalSupply = 0;
uint public multiplier = 1300000000000000000; // 1.3x to start
uint public bumpBasePrice = 10000000000000000; // 0.01 ETH
uint public holdTimeCeiling = 3628800; // 6 weeks in seconds
address public medianizerAddress;
Medianizer oracle;
bool public isMCD = false;
uint public MCDswitchTimestamp = 0;
address public saiAddress;
address public daiAddress;
Dai dai;
Dai sai;
constructor(address _medianizerAddress, address _saiAddress) public {
medianizerAddress = _medianizerAddress;
oracle = Medianizer(medianizerAddress);
saiAddress = _saiAddress;
dai = Dai(saiAddress);
sai = dai;
}
/**
* Constants
*/
string public constant name = "REKT.fyi";
string public constant symbol = "REKT";
uint8 public constant decimals = 0;
uint public constant WAD = 1000000000000000000;
uint public constant PRECISION = 100000000000000; // 4 orders of magnitude / decimal places
uint public constant MULTIPLIER_FLOOR = 1000000000000000000; // 1x
uint public constant MULTIPLIER_CEILING = 10000000000000000000; // 10x
uint public constant BONUS_FLOOR = 1250000000000000000; //1.25x
uint public constant BONUS_CEILING = 1800000000000000000; //1.8x
uint public constant BOUNTY_BONUS_MINIMUM = 5000000000000000000; // $5
uint public constant HOLD_SCORE_CEILING = 1000000000000000000000000000; // 1 RAY
uint public constant BUMP_INCREMENT = 100000000000000000; // 0.1x
uint public constant HOLD_TIME_MAX = 23670000; // 9 months is the maximum the owner can set with setHoldTimeCeiling(uint)
uint public constant BUMP_PRICE_MAX = 100000000000000000; //0.1 ETH is the maximum the owner can set with setBumpPrice(uint)
/**
* Events
*/
event LogVaultDeposit(address indexed addr, string indexed potType, uint value);
event LogWithdraw(address indexed to, uint eth, uint sai, uint dai);
event Transfer(address indexed from, address indexed to, uint tokens);
event LogBump(uint indexed from, uint indexed to, uint cost, address indexed by);
event LogBurn(
address indexed sender,
address indexed receiver,
uint receivedAt,
uint multiplier,
uint initialETH,
uint etherPrice,
uint bountyETH,
uint bountyDAI,
uint reward
);
event LogGive(address indexed sender, address indexed receiver);
/**
* Modifiers
*/
modifier shutdownNotActive() {
require(shutdown == false, "shutdown activated");
_;
}
modifier giveRequirementsMet(address _to) {
require(address(_to) != address(0), "Invalid address");
require(_to != msg.sender, "Cannot give to yourself");
require(balanceOf(_to) == 0, "Receiver already has a token");
require(_to.balance > 0, "Receiver wallet must not be empty");
_;
}
/**
* External functions
*/
/// @notice Give somebody a REKT token, along with an optional bounty in ether.
/// @param _to The address to send the REKT token to.
function give(address _to) external payable shutdownNotActive giveRequirementsMet(_to) {
if (msg.value > 0) {
unredeemedBounty[msg.sender].ETH = unredeemedBounty[msg.sender].ETH.add(msg.value);
bountyPot.ETH = bountyPot.ETH.add(msg.value);
}
receiver[_to] = Receiver(_to.balance, msg.value, 0, now, getPrice(), msg.sender);
giveCommon(_to);
}
/// @notice Give somebody a REKT token, along with an option bounty in DAI.
/// @param _to The account to send the REKT token to.
/// @param _amount The amount of DAI to use as a bounty.
function giveWithDAI(address _to, uint _amount) external shutdownNotActive giveRequirementsMet(_to) {
if (_amount > 0) {
// If the switch has already been included in this block then MCD is active,
// but we won't be able to tell later if that's the case so block this tx.
// Its ok for the mcd switch to occur later than this function in the same block
require(MCDswitchTimestamp != now, "Cannot send DAI during the switching block");
require(dai.transferFrom(msg.sender, address(this), _amount), "DAI transfer failed");
unredeemedBounty[msg.sender].DAI = unredeemedBounty[msg.sender].DAI.add(_amount);
bountyPot.DAI = bountyPot.DAI.add(_amount);
}
receiver[_to] = Receiver(_to.balance, 0, _amount, now, getPrice(), msg.sender);
giveCommon(_to);
}
/// @notice Bump the multiplier up or down.
/// @dev Multiplier has PRECISION precision and is rounded down unless the unrounded
/// value hits the MULTIPLIER_CEILING or MULTIPLIER_FLOOR.
/// @param _up Boolean representing whether the direction of the bump is up or not.
function bump(bool _up) external payable shutdownNotActive {
require(msg.value > 0, "Ether required");
uint initialMultiplier = multiplier;
// amount = (value/price)*bonus*increment
uint bumpAmount = msg.value
.wdiv(bumpBasePrice)
.wmul(getBonusMultiplier(msg.sender))
.wmul(BUMP_INCREMENT);
if (_up) {
if (multiplier.add(bumpAmount) >= MULTIPLIER_CEILING) {
multiplier = MULTIPLIER_CEILING;
} else {
multiplier = multiplier.add(roundBumpAmount(bumpAmount));
}
}
else {
if (multiplier > bumpAmount) {
if (multiplier.sub(bumpAmount) <= MULTIPLIER_FLOOR) {
multiplier = MULTIPLIER_FLOOR;
} else {
multiplier = multiplier.sub(roundBumpAmount(bumpAmount));
}
}
else {
multiplier = MULTIPLIER_FLOOR;
}
}
emit LogBump(initialMultiplier, multiplier, msg.value, msg.sender);
feePot = feePot.add(msg.value);
}
/// @notice Burn a REKT token. If applicable, fee reward and bounty are sent to user's pots.
/// REKT tokens can only be burned if the receiver has made gains >= the multiplier
/// (unless we are in shutdown mode).
/// @param _receiver The account that currently holds the REKT token.
function burn(address _receiver) external {
require(balanceOf(_receiver) == 1, "Nothing to burn");
address sender = receiver[_receiver].sender;
require(
msg.sender == _receiver ||
msg.sender == sender ||
(_receiver == address(this) && msg.sender == owner),
"Must be token sender or receiver, or must be the owner burning REKT sent to the contract"
);
if (!shutdown) {
if (receiver[_receiver].walletBalance.wmul(multiplier) > _receiver.balance) {
uint balanceValueThen = receiver[_receiver].walletBalance.wmul(receiver[_receiver].etherPrice);
uint balanceValueNow = _receiver.balance.wmul(getPrice());
if (balanceValueThen.wmul(multiplier) > balanceValueNow) {
revert("Not enough gains");
}
}
}
balance[_receiver] = 0;
totalSupply --;
emit Transfer(_receiver, address(0), 1);
uint feeReward = distributeBurnRewards(_receiver, sender);
emit LogBurn(
sender,
_receiver,
receiver[_receiver].timestamp,
multiplier,
receiver[_receiver].walletBalance,
receiver[_receiver].etherPrice,
receiver[_receiver].bountyETH,
receiver[_receiver].bountyDAI,
feeReward);
}
/// @notice Withdrawal of fee reward, DAI, SAI & ETH bounties for the user.
/// @param _addr The account to receive the funds and whose vault the funds will be taken from.
function withdraw(address payable _addr) external {
require(_addr != address(this), "This contract cannot withdraw to itself");
withdrawCommon(_addr, _addr);
}
/// @notice Withdraw from the contract's personal vault should anyone send
/// REKT to REKT.fyi with a bounty.
/// @param _destination The account to receive the funds.
function withdrawSelf(address payable _destination) external onlyOwner {
withdrawCommon(_destination, address(this));
}
/// @dev Sets a new Medianizer address in case of MakerDAO upgrades.
/// @param _addr The new address.
function setNewMedianizer(address _addr) external onlyOwner {
require(address(_addr) != address(0), "Invalid address");
medianizerAddress = _addr;
oracle = Medianizer(medianizerAddress);
bytes32 price;
bool ok;
(price, ok) = oracle.peek();
require(ok, "Pricefeed error");
}
/// @notice Sets a new DAI token address when MakerDAO upgrades to multicollateral DAI.
/// @dev DAI will now be deposited into vault[user].bountyDAI for new bounties instead
/// of vault[user].bountySAI.
/// If setMCD(address) has been included in the block already, then a user will
/// not be able to give a SAI/DAI bounty later in this block.
/// We can then determine with certainty whether they sent SAI or DAI when the time
/// comes to distribute it to a user's vault.
/// New DAI token can only be set once;
/// further changes will require shutdown and redeployment.
/// @param _addr The new address.
function setMCD(address _addr) external onlyOwner {
require(!isMCD, "MCD has already been set");
require(address(_addr) != address(0), "Invalid address");
daiAddress = _addr;
dai = Dai(daiAddress);
isMCD = true;
MCDswitchTimestamp = now;
}
/// @dev Sets a new bump price up to BUMP_PRICE_MAX.
/// @param _amount The base price of bumping by BUMP_INCREMENT.
function setBumpPrice(uint _amount) external onlyOwner {
require(_amount > 0 && _amount <= BUMP_PRICE_MAX, "Price must not be higher than BUMP_PRICE_MAX");
bumpBasePrice = _amount;
}
/// @dev Sets a new hold time ceiling up to HOLD_TIME_MAX.
/// @param _seconds The maximum hold time in seconds before the holdscore becomes 1 RAY.
function setHoldTimeCeiling(uint _seconds) external onlyOwner {
require(_seconds > 0 && _seconds <= HOLD_TIME_MAX, "Hold time must not be higher than HOLD_TIME_MAX");
holdTimeCeiling = _seconds;
}
/// @dev Permanent shutdown of the contract.
/// No one can give or bump, everyone can burn and withdraw.
function setShutdown() external onlyOwner {
shutdown = true;
}
/**
* Public functions
*/
/// @dev The proportion of the value of this bounty in relation to
/// the value of all bounties in the system.
/// @param _bounty This bounty.
/// @return A uint representing the proportion of bounty as a RAY.
function calculateBountyProportion(uint _bounty) public view returns (uint) {
return _bounty.rdiv(potValue(bountyPot.DAI, bountyPot.ETH));
}
/// @dev A score <= 1 RAY that corresponds to a duration between 0 and HOLD_SCORE_CEILING.
/// @params _receivedAtTime The timestamp of the block where the user received the REKT token.
/// @return A uint representing the score as a RAY.
function calculateHoldScore(uint _receivedAtTime) public view returns (uint) {
if (now == _receivedAtTime)
{
return 0;
}
uint timeDiff = now.sub(_receivedAtTime);
uint holdScore = timeDiff.rdiv(holdTimeCeiling);
if (holdScore > HOLD_SCORE_CEILING) {
holdScore = HOLD_SCORE_CEILING;
}
return holdScore;
}
/// @notice Returns the REKT balance of the specified address.
/// @dev Effectively a bool because the balance can only be 0 or 1.
/// @param _owner The address to query the balance of.
/// @return A uint representing the amount owned by the passed address.
function balanceOf(address _receiver) public view returns (uint) {
return balance[_receiver];
}
/// @notice Returns the total value of _dai and _eth in USD. 1 DAI = $1 is assumed.
/// @dev Price of ether taken from MakerDAO's Medianizer via getPrice().
/// @param _dai DAI to use in calculation.
/// @param _eth Ether to use in calculation.
/// @return A uint representing the total value of the inputs.
function potValue(uint _dai, uint _eth) public view returns (uint) {
return _dai.add(_eth.wmul(getPrice()));
}
/// @dev Returns the bonus multiplier represented as a WAD.
/// @param _sender The address of the sender.
/// @return A uint representing the bonus multiplier as a WAD.
function getBonusMultiplier(address _sender) public view returns (uint) {
uint bounty = potValue(unredeemedBounty[_sender].DAI, unredeemedBounty[_sender].ETH);
uint bonus = WAD;
if (bounty >= BOUNTY_BONUS_MINIMUM) {
bonus = bounty.wdiv(potValue(bountyPot.DAI, bountyPot.ETH)).add(BONUS_FLOOR);
if (bonus > BONUS_CEILING) {
bonus = BONUS_CEILING;
}
}
return bonus;
}
/// @dev Returns the addresses the sender has sent to as an array.
/// @param _sender The address of the sender.
/// @return An array of recipient addresses.
function getRecipients(address _sender) public view returns (address[] memory) {
return recipients[_sender];
}
/// @dev Returns the price of ETH in USD as per the MakerDAO Medianizer interface.
/// @return A uint representing the price of ETH in USD as a WAD.
function getPrice() public view returns (uint) {
bytes32 price;
bool ok;
(price, ok) = oracle.peek();
require(ok, "Pricefeed error");
return uint(price);
}
/**
* Private functions
*/
/// @dev Common functionality for give(address) and giveWithDAI(address, uint).
/// @param _to The account to send the REKT token to.
function giveCommon(address _to) private {
balance[_to] = 1;
recipients[msg.sender].push(_to);
totalSupply ++;
emit Transfer(address(0), msg.sender, 1);
emit Transfer(msg.sender, _to, 1);
emit LogGive(msg.sender, _to);
}
/// @dev Assigns rewards and bounties to pots within user vaults dependant on holdScore
/// and bounty proportion compared to the total bounties within the system.
/// @param _receiver The account that received the REKT token.
/// @param _sender The account that sent the REKT token.
/// @return A uint representing the fee reward.
function distributeBurnRewards(address _receiver, address _sender) private returns (uint feeReward) {
feeReward = 0;
uint bountyETH = receiver[_receiver].bountyETH;
uint bountyDAI = receiver[_receiver].bountyDAI;
uint bountyTotal = potValue(bountyDAI, bountyETH);
if (bountyTotal > 0 ) {
uint bountyProportion = calculateBountyProportion(bountyTotal);
uint userRewardPot = bountyProportion.rmul(feePot);
if (shutdown) {
// in the shutdown state the holdscore isn't used
feeReward = userRewardPot;
} else {
uint holdScore = calculateHoldScore(receiver[_receiver].timestamp);
feeReward = userRewardPot.rmul(holdScore);
}
if (bountyETH > 0) {
// subtract bounty from the senders's bounty total and the bounty pot
unredeemedBounty[_sender].ETH = unredeemedBounty[_sender].ETH.sub(bountyETH);
bountyPot.ETH = bountyPot.ETH.sub(bountyETH);
// add bounty to receivers vault
vault[_receiver].bountyETH = vault[_receiver].bountyETH.add(bountyETH);
emit LogVaultDeposit(_receiver, 'bountyETH', bountyETH);
} else if (bountyDAI > 0) {
unredeemedBounty[_sender].DAI = unredeemedBounty[_sender].DAI.sub(bountyDAI);
bountyPot.DAI = bountyPot.DAI.sub(bountyDAI);
if (isMCD && receiver[_receiver].timestamp > MCDswitchTimestamp) {
vault[_receiver].bountyDAI = vault[_receiver].bountyDAI.add(bountyDAI);
} else { // they would have sent SAI
vault[_receiver].bountySAI = vault[_receiver].bountySAI.add(bountyDAI);
}
emit LogVaultDeposit(_receiver, 'bountyDAI', bountyDAI);
}
if (feeReward > 0) {
feeReward = feeReward / 2;
// subtract and add feeReward for receiver vault
feePot = feePot.sub(feeReward);
vault[_receiver].fee = vault[_receiver].fee.add(feeReward);
emit LogVaultDeposit(_receiver, 'reward', feeReward);
// subtract and add feeReward for sender vault
feePot = feePot.sub(feeReward);
vault[_sender].fee = vault[_sender].fee.add(feeReward);
emit LogVaultDeposit(_sender, 'reward', feeReward);
}
}
return feeReward;
}
/// @dev Returns a rounded bump amount represented as a WAD.
/// @param _amount The amount to be rounded.
/// @return A uint representing the amount rounded to PRECISION as a WAD.
function roundBumpAmount(uint _amount) private pure returns (uint rounded) {
require(_amount >= PRECISION, "bump size too small to round");
return (_amount / PRECISION).mul(PRECISION);
}
/// @dev called by withdraw(address) and withdrawSelf(address) to withdraw
/// fee reward, DAI, SAI & ETH bounties.
/// Both params will be the same for a normal user withdrawal.
/// @param _destination The account to receive the funds.
/// @param _vaultOwner The vault that the funds will be taken from.
function withdrawCommon(address payable _destination, address _vaultOwner) private {
require(address(_destination) != address(0), "Invalid address");
uint amountETH = vault[_vaultOwner].fee.add(vault[_vaultOwner].bountyETH);
uint amountDAI = vault[_vaultOwner].bountyDAI;
uint amountSAI = vault[_vaultOwner].bountySAI;
vault[_vaultOwner] = Vault(0,0,0,0);
emit LogWithdraw(_destination, amountETH, amountSAI, amountDAI);
if (amountDAI > 0) {
require(dai.transferFrom(address(this), _destination, amountDAI), "DAI transfer failed");
}
if (amountSAI > 0) {
require(sai.transferFrom(address(this), _destination, amountSAI), "SAI transfer failed");
}
if (amountETH > 0) {
_destination.transfer(amountETH);
}
}
} | Sets a new Medianizer address in case of MakerDAO upgrades. _addr The new address. | function setNewMedianizer(address _addr) external onlyOwner {
require(address(_addr) != address(0), "Invalid address");
medianizerAddress = _addr;
oracle = Medianizer(medianizerAddress);
bytes32 price;
bool ok;
(price, ok) = oracle.peek();
require(ok, "Pricefeed error");
}
| 1,033,125 |
// File: openzeppelin\contracts\utils\introspection\IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin\contracts\token\ERC721\IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: openzeppelin\contracts\token\ERC721\extensions\IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: openzeppelin\contracts\token\ERC721\IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: openzeppelin\contracts\security\ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: bapestoken.sol
interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IPancakeERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface IPancakeFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IPancakeRouter01 {
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function factory() external pure returns (address);
function WETH() external pure returns (address);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IPancakeRouter02 is IPancakeRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//BallerX Contract ////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
contract BAPE is IBEP20, Ownable, IERC721Receiver, ReentrancyGuard
{
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
EnumerableSet.AddressSet private _excluded;
//Token Info
string private constant _name = 'BAPE';
string private constant _symbol = 'BAPE';
uint8 private constant _decimals = 9;
uint256 public constant InitialSupply= 1 * 10**9 * 10**_decimals;
uint256 swapLimit = 5 * 10**6 * 10**_decimals; // 0,5%
bool isSwapPegged = false;
//Divider for the buyLimit based on circulating Supply (1%)
uint16 public constant BuyLimitDivider=1;
//Divider for the MaxBalance based on circulating Supply (1.5%)
uint8 public constant BalanceLimitDivider=1;
//Divider for the Whitelist MaxBalance based on initial Supply(1.5%)
uint16 public constant WhiteListBalanceLimitDivider=1;
//Divider for sellLimit based on circulating Supply (1%)
uint16 public constant SellLimitDivider=100;
// Chef address
address public chefAddress = 0x000000000000000000000000000000000000dEaD;
// Limits control
bool sellLimitActive = true;
bool buyLimitActive = true;
bool balanceLimitActive = true;
// Team control switch
bool _teamEnabled = true;
// Team wallets
address public constant marketingWallet=0xECB1C6fa4fAea49047Fa0748B0a1d30136Baa73F;
address public constant developmentWallet=0x4223b10d22bF8634d5128F588600C65F854cd20c;
address public constant charityWallet=0x65685081E64FCBD2377C95E5ccb6167ff5f503d3;
// Uniswap v2 Router
address private constant PancakeRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// Cooldown vars
bool cooldown = true;
mapping(address => bool) hasTraded;
mapping(address => uint256) lastTrade;
uint256 cooldownTime = 1 seconds;
//variables that track balanceLimit and sellLimit,
//can be updated based on circulating supply and Sell- and BalanceLimitDividers
uint256 private _circulatingSupply =InitialSupply;
uint256 public balanceLimit = _circulatingSupply;
uint256 public sellLimit = _circulatingSupply;
uint256 public buyLimit = _circulatingSupply;
address[] public triedToDump;
//Limits max tax, only gets applied for tax changes, doesn't affect inital Tax
uint8 public constant MaxTax=49;
// claim Settings
uint256 public claimFrequency = 86400 seconds;
mapping(address => uint256) private _nftHolderLastTransferTimestamp;
mapping(uint256 => uint256) private _nftStakeTime;
mapping(uint256 => uint256) private _nftStakePeriod;
bool public claimEnabled = true;
bool public checkTxSigner = true;
bool public checkClaimFrequency = true;
bool public checkTxMsgSigner = true;
address private passwordSigner = 0x81bEE9fF7f8d1D9c32B7BB5714A4236e078E9eCC;
mapping(uint256 => bool) private _txMsgSigner;
//Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer
uint8 private _buyTax;
uint8 private _sellTax;
uint8 private _transferTax;
uint8 private _liquidityTax;
uint8 private _distributedTax;
bool isTokenSwapManual = true;
address private _pancakePairAddress;
IPancakeRouter02 private _pancakeRouter;
//modifier for functions only the team can call
modifier onlyTeam() {
require(_isTeam(msg.sender), "Caller not in Team");
_;
}
modifier onlyChef() {
require(_isChef(msg.sender), "Caller is not chef");
_;
}
//Checks if address is in Team, is needed to give Team access even if contract is renounced
//Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks)
function _isTeam(address addr) private view returns (bool){
if(!_teamEnabled) {
return false;
}
return addr==owner()||addr==marketingWallet||addr==charityWallet||addr==developmentWallet;
}
function _isChef(address addr) private view returns (bool) {
return addr==chefAddress;
}
//erc1155 receiver
//addresses
using EnumerableSet for EnumerableSet.UintSet;
address nullAddress = 0x0000000000000000000000000000000000000000;
address public bapesNftAddress;
// mappings
mapping(address => EnumerableSet.UintSet) private _deposits;
bool public _addBackLiquidity = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Constructor///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
constructor () {
//contract creator gets 90% of the token to create LP-Pair
uint256 deployerBalance=_circulatingSupply*9/10;
_balances[msg.sender] = deployerBalance;
emit Transfer(address(0), msg.sender, deployerBalance);
//contract gets 10% of the token to generate LP token and Marketing Budget fase
//contract will sell token over the first 200 sells to generate maximum LP and BNB
uint256 injectBalance=_circulatingSupply-deployerBalance;
_balances[address(this)]=injectBalance;
emit Transfer(address(0), address(this),injectBalance);
// Pancake Router
_pancakeRouter = IPancakeRouter02(PancakeRouter);
//Creates a Pancake Pair
_pancakePairAddress = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH());
//Sets Buy/Sell limits
balanceLimit=InitialSupply/BalanceLimitDivider;
sellLimit=InitialSupply/SellLimitDivider;
buyLimit=InitialSupply/BuyLimitDivider;
_buyTax=8;
_sellTax=10;
_transferTax=0;
_distributedTax=100;
_liquidityTax=0;
//Team wallet and deployer are excluded from Taxes
_excluded.add(charityWallet);
_excluded.add(developmentWallet);
_excluded.add(marketingWallet);
_excluded.add(developmentWallet);
_excluded.add(msg.sender);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Transfer functionality////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//transfer function, every transfer runs through this function
function _transfer(address sender, address recipient, uint256 amount) private{
require(sender != address(0), "Transfer from zero");
require(recipient != address(0), "Transfer to zero");
//Manually Excluded adresses are transfering tax and lock free
bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient));
//Transactions from and to the contract are always tax and lock free
bool isContractTransfer=(sender==address(this) || recipient==address(this));
//transfers between PancakeRouter and PancakePair are tax and lock free
address pancakeRouter=address(_pancakeRouter);
bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter)
|| (recipient == _pancakePairAddress && sender == pancakeRouter));
//differentiate between buy/sell/transfer to apply different taxes/restrictions
bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter;
bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter;
//Pick transfer
if(isContractTransfer || isLiquidityTransfer || isExcluded){
_feelessTransfer(sender, recipient, amount);
} else{
require(tradingEnabled, "Trading is disabled");
// Cooldown logic (excluded people have no cooldown and contract too)
if(cooldown) {
if (hasTraded[msg.sender]) {
lastTrade[msg.sender] = block.timestamp;
require(block.timestamp < (lastTrade[msg.sender] + cooldownTime));
} else {
hasTraded[msg.sender] = true;
}
}
_taxedTransfer(sender,recipient,amount,isBuy,isSell);
}
}
//applies taxes, checks for limits, locks generates autoLP and stakingBNB, and autostakes
function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{
uint256 recipientBalance = _balances[recipient];
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
swapLimit = sellLimit/2;
uint8 tax;
if(isSell){
if (sellLimitActive) {
require(amount<=sellLimit,"Dump protection");
}
tax=_sellTax;
} else if(isBuy){
//Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
if (balanceLimitActive) {
require(recipientBalance+amount<=(balanceLimit*2),"whale protection");
}
if (buyLimitActive) {
require(amount<=buyLimit, "whale protection");
}
tax=_buyTax;
} else {//Transfer
//Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
require(recipientBalance+amount<=balanceLimit,"whale protection");
//Transfers are disabled in sell lock, this doesn't stop someone from transfering before
//selling, but there is no satisfying solution for that, and you would need to pax additional tax
tax=_transferTax;
}
//Swapping AutoLP and MarketingBNB is only possible if sender is not pancake pair,
//if its not manually disabled, if its not already swapping and if its a Sell to avoid
// people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens
if((sender!=_pancakePairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier))
_swapContractToken(amount);
//staking and liquidity Tax get treated the same, only during conversion they get split
uint256 contractToken=_calculateFee(amount, tax, _distributedTax+_liquidityTax);
//Subtract the Taxed Tokens from the amount
uint256 taxedAmount=amount-(contractToken);
//Removes token and handles staking
_removeToken(sender,amount);
//Adds the taxed tokens to the contract wallet
_balances[address(this)] += contractToken;
//Adds token and handles staking
_addToken(recipient, taxedAmount);
emit Transfer(sender,recipient,taxedAmount);
}
//Feeless transfer only transfers and autostakes
function _feelessTransfer(address sender, address recipient, uint256 amount) private{
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
//Removes token and handles staking
_removeToken(sender,amount);
//Adds token and handles staking
_addToken(recipient, amount);
emit Transfer(sender,recipient,amount);
}
//Calculates the token that should be taxed
function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) {
return (amount*tax*taxPercent) / 10000;
}
//removes Token, adds BNB to the toBePaid mapping and resets staking
function _removeToken(address addr, uint256 amount) private {
//the amount of token after transfer
uint256 newAmount=_balances[addr]-amount;
_balances[address(this)] += amount;
_balances[addr]=newAmount;
emit Transfer(addr, address(this), amount);
}
//lock for the withdraw
bool private _isTokenSwaping;
//the total reward distributed through staking, for tracking purposes
uint256 public totalTokenSwapGenerated;
//the total payout through staking, for tracking purposes
uint256 public totalPayouts;
//marketing share of the TokenSwap tax
uint8 public _marketingShare=40;
//marketing share of the TokenSwap tax
uint8 public _charityShare=20;
//marketing share of the TokenSwap tax
uint8 public _developmentShare=40;
//balance that is claimable by the team
uint256 public marketingBalance;
uint256 public developmentBalance;
uint256 public charityBalance;
//Mapping of shares that are reserved for payout
mapping(address => uint256) private toBePaid;
//distributes bnb between marketing, development and charity
function _distributeFeesBNB(uint256 BNBamount) private {
// Deduct marketing Tax
uint256 marketingSplit = (BNBamount * _marketingShare) / 100;
uint256 charitySplit = (BNBamount * _charityShare) / 100;
uint256 developmentSplit = (BNBamount * _developmentShare) / 100;
// Safety check to avoid solidity division imprecision
if ((marketingSplit+charitySplit+developmentSplit) > address(this).balance) {
uint256 toRemove = (marketingSplit+charitySplit+developmentSplit) - address(this).balance;
developmentSplit -= toRemove;
}
// Updating balances
marketingBalance+=marketingSplit;
charityBalance+=charitySplit;
developmentBalance += developmentSplit;
}
function _addToken(address addr, uint256 amount) private {
//the amount of token after transfer
uint256 newAmount=_balances[addr]+amount;
_balances[addr]=newAmount;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Swap Contract Tokens//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
//tracks auto generated BNB, useful for ticker etc
uint256 public totalLPBNB;
//Locks the swap if already swapping
bool private _isSwappingContractModifier;
modifier lockTheSwap {
_isSwappingContractModifier = true;
_;
_isSwappingContractModifier = false;
}
//swaps the token on the contract for Marketing BNB and LP Token.
//always swaps the sellLimit of token to avoid a large price impact
function _swapContractToken(uint256 totalMax) private lockTheSwap{
uint256 contractBalance=_balances[address(this)];
uint16 totalTax=_liquidityTax+_distributedTax;
uint256 tokenToSwap=swapLimit;
if(tokenToSwap > totalMax) {
if(isSwapPegged) {
tokenToSwap = totalMax;
}
}
//only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0
if(contractBalance<tokenToSwap||totalTax==0){
return;
}
//splits the token in TokenForLiquidity and tokenForMarketing
uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax;
uint256 tokenLeft = tokenToSwap - tokenForLiquidity;
//splits tokenForLiquidity in 2 halves
uint256 liqToken=tokenForLiquidity/2;
uint256 liqBNBToken=tokenForLiquidity-liqToken;
//swaps fees tokens and the liquidity token half for BNB
uint256 swapToken=liqBNBToken+tokenLeft;
//Gets the initial BNB balance, so swap won't touch any other BNB
uint256 initialBNBBalance = address(this).balance;
_swapTokenForBNB(swapToken);
uint256 newBNB=(address(this).balance - initialBNBBalance);
//calculates the amount of BNB belonging to the LP-Pair and converts them to LP
if(_addBackLiquidity)
{
uint256 liqBNB = (newBNB*liqBNBToken)/swapToken;
_addLiquidity(liqToken, liqBNB);
}
//Get the BNB balance after LP generation to get the
//exact amount of bnb left to distribute
uint256 generatedBNB=(address(this).balance - initialBNBBalance);
//distributes remaining BNB between stakers and Marketing
_distributeFeesBNB(generatedBNB);
}
//swaps tokens on the contract for BNB
function _swapTokenForBNB(uint256 amount) private {
_approve(address(this), address(_pancakeRouter), amount);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _pancakeRouter.WETH();
_pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0,
path,
address(this),
block.timestamp
);
}
//Adds Liquidity directly to the contract where LP are locked
function _addLiquidity(uint256 tokenamount, uint256 bnbamount) private {
totalLPBNB+=bnbamount;
_approve(address(this), address(_pancakeRouter), tokenamount);
_pancakeRouter.addLiquidityETH{value: bnbamount}(
address(this),
tokenamount,
0,
0,
address(this),
block.timestamp
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Settings//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool public sellLockDisabled;
uint256 public sellLockTime;
bool public manualConversion;
function mint(uint256 qty) public onlyChef {
_circulatingSupply = _circulatingSupply + qty;
_balances[chefAddress] = _balances[chefAddress] + qty;
emit Transfer(address(0), chefAddress, qty);
}
function mintClaim(address account,uint256 qty) internal {
_circulatingSupply = _circulatingSupply + qty;
_balances[account] = _balances[account] + qty;
emit Transfer(address(0), account, qty);
}
function burn(uint256 qty) public onlyChef {
_circulatingSupply = _circulatingSupply + qty;
_balances[chefAddress] = _balances[chefAddress] - qty;
emit Transfer(address(0), chefAddress, qty);
}
// Cooldown control
function isCooldownEnabled(bool booly) public onlyTeam {
cooldown = booly;
}
function setCooldownTime(uint256 time) public onlyTeam {
cooldownTime = time;
}
// This will DISABLE every control from the team
function renounceTeam() public onlyTeam {
_teamEnabled = false;
}
function TeamSetChef(address addy) public onlyTeam {
chefAddress = addy;
}
function TeamIsActiveSellLimit(bool booly) public onlyTeam {
sellLimitActive = booly;
}
function TeamIsActiveBuyLimit(bool booly) public onlyTeam {
buyLimitActive = booly;
}
function TeamIsActiveBalanceLimit(bool booly) public onlyTeam {
balanceLimitActive = booly;
}
function TeamEnableTrading() public onlyTeam {
tradingEnabled = true;
}
function TeamWithdrawMarketingBNB() public onlyTeam{
uint256 amount=marketingBalance;
marketingBalance=0;
(bool sent,) =marketingWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
function TeamWithdrawCharityBNB() public onlyTeam{
uint256 amount=charityBalance;
charityBalance=0;
(bool sent,) =charityWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
function TeamWithdrawDevelopmentBNB() public onlyTeam{
uint256 amount=developmentBalance;
developmentBalance=0;
(bool sent,) =developmentWallet.call{value: (amount)}("");
require(sent,"withdraw failed");
}
//switches autoLiquidity and marketing BNB generation during transfers
function TeamSwitchManualBNBConversion(bool manual) public onlyTeam{
manualConversion=manual;
}
//Sets Taxes, is limited by MaxTax(49%) to make it impossible to create honeypot
function TeamSetTaxes(uint8 distributedTaxes, uint8 liquidityTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{
uint8 totalTax=liquidityTaxes+distributedTaxes;
require(totalTax==100, "liq+distributed needs to equal 100%");
require(buyTax<=MaxTax&&sellTax<=MaxTax&&transferTax<=MaxTax,"taxes higher than max tax");
_liquidityTax=liquidityTaxes;
_distributedTax=distributedTaxes;
_buyTax=buyTax;
_sellTax=sellTax;
_transferTax=transferTax;
}
//manually converts contract token to LP and staking BNB
function TeamManualGenerateTokenSwapBalance(uint256 _qty) public onlyTeam{
_swapContractToken(_qty * 10**9);
}
//Exclude/Include account from fees (eg. CEX)
function TeamExcludeAccountFromFees(address account) public onlyTeam {
_excluded.add(account);
}
function TeamIncludeAccountToFees(address account) public onlyTeam {
_excluded.remove(account);
}
//Limits need to be at least 0.5%, to avoid setting value to 0(avoid potential Honeypot)
function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyTeam{
uint256 minimumLimit = 5 * 10**6;
//Adds decimals to limits
newBalanceLimit=newBalanceLimit*10**_decimals;
newSellLimit=newSellLimit*10**_decimals;
require(newBalanceLimit>=minimumLimit && newSellLimit>=minimumLimit, "Limit protection");
balanceLimit = newBalanceLimit;
sellLimit = newSellLimit;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup Functions///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool public tradingEnabled=false;
address private _liquidityTokenAddress;
//Enables whitelist trading and locks Liquidity for a short time
//Sets up the LP-Token Address required for LP Release
function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyTeam{
_liquidityTokenAddress=liquidityTokenAddress;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//external//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
receive() external payable {}
fallback() external payable {}
// IBEP20
function getOwner() external view override returns (address) {
return owner();
}
function name() external pure override returns (string memory) {
return _name;
}
function symbol() external pure override returns (string memory) {
return _symbol;
}
function decimals() external pure override returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _circulatingSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address _owner, address spender) external view override returns (uint256) {
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "Approve from zero");
require(spender != address(0), "Approve to zero");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "Transfer > allowance");
_approve(sender, msg.sender, currentAllowance - amount);
return true;
}
// IBEP20 - Helpers
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "<0 allowance");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
function checkLastClaim(address to) public view returns (uint256 )
{
return _nftHolderLastTransferTimestamp[to];
}
function gethash(address to,uint nid,uint nonce) public pure returns (bytes memory )
{
return abi.encodePacked(to, nid,nonce);
}
function getKeccak(address to,uint nid,uint nonce) public pure returns (bytes32)
{
return keccak256(gethash(to, nid,nonce));
}
function getKeccakHashed(address to,uint nid,uint nonce) public pure returns (bytes32)
{
return getEthSignedMessageHash(keccak256(gethash(to, nid,nonce)));
}
/* function checkSignature(address to,uint256 nid,uint256 nonce, bytes memory signature) public view returns (bool) {
bytes32 messageHash = keccak256(abi.encode(to, nid,nonce));
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == passwordSigner;
}
*/
function claimTokens(address to,uint256 amount,uint256 nounce, bytes memory signature) public {
require(claimEnabled, "Claim Disabled");
if(checkTxSigner)
{
require(verify(to, amount,nounce,signature), "Invalid Signature");
}
if(checkClaimFrequency)
{
require(block.timestamp > _nftHolderLastTransferTimestamp[to] + claimFrequency, "Not the Claim time.");
}
if(checkTxMsgSigner)
{
require(!_txMsgSigner[nounce], "Invalid Claim");
_txMsgSigner[nounce] = true;
_nftHolderLastTransferTimestamp[to] = block.timestamp;
}
_feelessTransfer(owner(), to, amount*10**9);
}
function getMessageHash(
address _to,
uint _amount,
uint _nonce
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_to, _amount, _nonce));
}
function getEthSignedMessageHash(bytes32 _messageHash)
public
pure
returns (bytes32)
{
/*
Signature is produced by signing a keccak256 hash with the following format:
"\x19Ethereum Signed Message\n" + len(msg) + msg
*/
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)
);
}
function verify(
address _to,
uint _amount,
uint _nonce,
bytes memory signature
) public view returns (bool) {
bytes32 messageHash = getMessageHash(_to, _amount, _nonce);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == passwordSigner;
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
public
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory sig)
public
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(sig.length == 65, "invalid signature length");
assembly {
/*
First 32 bytes stores the length of the signature
add(sig, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads next 32 bytes starting at the memory address p into memory
*/
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
// implicitly return (r, s, v)
}
function setnftClaimSettings(address _passwordSigner,uint256 _claimFrequency, bool _Enabled,bool _checkTxSigner,bool _checkTxMsgSigner,bool _checkClaimFrequency) external onlyOwner {
require(_claimFrequency >= 600, "cannot set clain more often than every 10 minutes");
claimFrequency = _claimFrequency;
passwordSigner = _passwordSigner;
claimEnabled = _Enabled;
checkTxSigner = _checkTxSigner;
checkClaimFrequency = _checkClaimFrequency;
checkTxMsgSigner = _checkTxMsgSigner;
}
//=======================erc1155 receiving
//alter rate and expiration
function updateNftAddress(address payable newFundsTo,bool addBackLiquidity) public onlyOwner {
bapesNftAddress = newFundsTo;
_addBackLiquidity = addBackLiquidity;
}
//check deposit amount.
function depositsOf(address account)
external
view
returns (uint256[] memory)
{
EnumerableSet.UintSet storage depositSet = _deposits[account];
uint256[] memory tokenIds = new uint256[] (depositSet.length());
for (uint256 i; i<depositSet.length(); i++) {
tokenIds[i] = depositSet.at(i);
}
return tokenIds;
}
//deposit function.
function deposit(uint256[] calldata tokenIds,uint256 prd) external {
//claimRewards(tokenIds);
for (uint256 i; i < tokenIds.length; i++) {
_nftStakeTime[tokenIds[i]] = block.timestamp;
_nftStakePeriod[tokenIds[i]] = prd;
IERC721(bapesNftAddress).safeTransferFrom(
msg.sender,
address(this),
tokenIds[i],
''
);
_deposits[msg.sender].add(tokenIds[i]);
}
}
function getNftStakeTime(uint256 tid) public view returns (uint256)
{
return _nftStakeTime[tid];
}
function getNftStakePeriod(uint256 tid) public view returns (uint256)
{
return _nftStakePeriod[tid];
}
//withdrawal function.
function withdraw(address to,uint256 amount,uint256 nounce, bytes memory signature,uint256[] calldata tokenIds) external nonReentrant() {
// claimRewards(tokenIds);
if(amount>0)
{
require(verify(to, amount,nounce,signature), "Invalid Signature");
require(!_txMsgSigner[nounce], "Invalid Claim");
_txMsgSigner[nounce] = true;
//_nftHolderLastTransferTimestamp[to] = block.timestamp;
}
for (uint256 i; i < tokenIds.length; i++) {
require(
_deposits[msg.sender].contains(tokenIds[i]),
'Staking: token not deposited'
);
_nftStakeTime[tokenIds[i]] = 0;
_deposits[msg.sender].remove(tokenIds[i]);
IERC721(bapesNftAddress).safeTransferFrom(
address(this),
msg.sender,
tokenIds[i],
''
);
}
if(amount>0)
{
mintClaim(to, amount*10**9);
}
// _feelessTransfer(owner(), to, amount*10**9);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
} | Sets Taxes, is limited by MaxTax(49%) to make it impossible to create honeypot | function TeamSetTaxes(uint8 distributedTaxes, uint8 liquidityTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{
uint8 totalTax=liquidityTaxes+distributedTaxes;
require(totalTax==100, "liq+distributed needs to equal 100%");
require(buyTax<=MaxTax&&sellTax<=MaxTax&&transferTax<=MaxTax,"taxes higher than max tax");
_liquidityTax=liquidityTaxes;
_distributedTax=distributedTaxes;
_buyTax=buyTax;
_sellTax=sellTax;
_transferTax=transferTax;
}
| 11,949,426 |
./full_match/97/0xAFF60E6d6119D7807247809B4D39995dA2E0eF92/sources/project:/contracts/tokens/CELLIT.sol | Moves amount tokens from the caller's account to recipient. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. recipient address of user amount amount of token that you want to send/ | function transfer(address recipient, uint amount) external override whenNotPaused returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
| 3,274,483 |
./full_match/5/0x06775aB363873FcCf9f4E5Bb15f6216235Adb10F/sources/_openzeppelin/contracts-upgradeable/utils/CheckpointsUpgradeable.sol | Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will be set to `op(latest, delta)`. Returns previous value and new value./ | function push(
History storage self,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) internal returns (uint256, uint256) {
return push(self, op(latest(self), delta));
}
| 1,855,181 |
./full_match/43113/0xE2bB15cC65dADC1Ca22540cC5024f87EE980edb6/sources/contracts/minita_yak.sol | YAK_token.approve(address(joeRouter), YAK_token.balanceOf(address(this))); otherToken.transfer(tx.origin, amountReceived.sub(amountRequired)); | function joeCall(
address _sender,
uint _amount1,
bytes calldata _data
) external {
msg.sender == 0x85e355d284082D2E8C5BDb88a3D9D1c1d0347bB5;
address[] memory pathMiniYakWavax = new address[](2);
uint256 amountRequired = JoeLibrary.getAmountsIn(joeFactory, amountToken, pathMiniYakWavax)[0];
require(amountRequired != 0,'no se pudo calcular el amountRequired ');
require(amountToken!=IMiniYak(miniYak).balanceOf(address(this)),'no llegaron los miniyak');
address[] memory pathYakWaxax = new address[](2);
IMiniYak(miniYak).unmoon(amountToken, address(this));
require(YAK_token.balanceOf(address(this)) == 0,'no llegaron los yak');
uint amountReceived = joeRouter.swapExactTokensForTokens(
YAK_token.balanceOf(address(this)),
0,
pathYakWaxax,
address(this),
block.timestamp + deadline
)[1];
require(amountReceived != 0,'no llegaron los wavax');
require(amountReceived <= amountRequired,'falto WAVAX');
IJoeERC20 otherToken = IJoeERC20(WAVAX);
otherToken.transfer(msg.sender, amountRequired);
}
| 13,199,003 |
pragma solidity ^0.4.10;
/**
* Hodld DAO and ERC20 token
* Author: CurrencyTycoon on GitHub
* License: MIT
* Date: 2017
*
* Deploy with the following args:
* 0, "Hodl DAO", 18, "HODL"
*
*/
contract HodlDAO {
/* ERC20 Public variables of the token */
string public version = 'HDAO 0.2';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* ERC20 This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* store the block number when a withdrawal has been requested*/
mapping (address => withdrawalRequest) public withdrawalRequests;
struct withdrawalRequest {
uint sinceBlock;
uint256 amount;
}
/**
* feePot collects fees from quick withdrawals. This gets re-distributed to slow-withdrawals
*/
uint256 public feePot;
uint32 public constant blockWait = 172800; // roughly 30 days, (2592000 / 15) - assuming block time is ~15 sec.
//uint public constant blockWait = 8; // roughly assuming block time is ~15 sec.
/**
* ERC20 events these generate a public event on the blockchain that will notify clients
*/
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event WithdrawalQuick(address indexed by, uint256 amount, uint256 fee); // quick withdrawal done
event InsufficientFee(address indexed by, uint256 feeRequired); // not enough fee paid for quick withdrawal
event WithdrawalStarted(address indexed by, uint256 amount);
event WithdrawalDone(address indexed by, uint256 amount, uint256 reward); // amount is the amount that was used to calculate reward
event WithdrawalPremature(address indexed by, uint blocksToWait); // Needs to wait blocksToWait before withdrawal unlocked
event Deposited(address indexed by, uint256 amount);
/**
* Initializes contract with initial supply tokens to the creator of the contract
* In our case, there's no initial supply. Tokens will be created as ether is sent
* to the fall-back function. Then tokens are burned when ether is withdrawn.
*/
function HodlDAO(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
}
/**
* notPendingWithdrawal modifier guards the function from executing when a
* withdrawal has been requested and is currently pending
*/
modifier notPendingWithdrawal {
if (withdrawalRequests[msg.sender].sinceBlock > 0) throw;
_;
}
/** ERC20 - transfer sends tokens
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) notPendingWithdrawal {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/** ERC20 approve allows another contract to spend some tokens in your behalf
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value) notPendingWithdrawal
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* ERC-20 Approves and then calls the receiving contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) notPendingWithdrawal
returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
/**
* ERC20 A contract attempts to get the coins
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint256 _value) notPendingWithdrawal
returns (bool success) {
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/**
* withdrawalInitiate initiates the withdrawal by going into a waiting period
* It remembers the block number & amount held at the time of request.
* After the waiting period finishes, the call withdrawalComplete
*/
function withdrawalInitiate() notPendingWithdrawal {
WithdrawalStarted(msg.sender, balanceOf[msg.sender]);
withdrawalRequests[msg.sender] = withdrawalRequest(block.number, balanceOf[msg.sender]);
}
/**
* withdrawalComplete is called after the waiting period. The ether will be
* returned to the caller and the tokens will be burned.
* A reward will be issued based on the amount in the feePot relative to the
* amount held when the withdrawal request was made.
*
* Gas: 17008
*/
function withdrawalComplete() returns (bool) {
withdrawalRequest r = withdrawalRequests[msg.sender];
if (r.sinceBlock == 0) throw;
if ((r.sinceBlock + blockWait) > block.number) {
WithdrawalPremature(msg.sender, r.sinceBlock + blockWait - block.number);
return false;
}
uint256 amount = withdrawalRequests[msg.sender].amount;
uint256 reward = calculateReward(r.amount);
withdrawalRequests[msg.sender].sinceBlock = 0;
withdrawalRequests[msg.sender].amount = 0;
if (reward > 0) {
if (feePot - reward > feePot) {
feePot = 0; // overflow
} else {
feePot -= reward;
}
}
doWithdrawal(reward);
WithdrawalDone(msg.sender, amount, reward);
return true;
}
/**
* Reward is based on the amount held, relative to total supply of tokens.
*/
function calculateReward(uint256 v) constant returns (uint256) {
uint256 reward = 0;
if (feePot > 0) {
reward = v / totalSupply * feePot;
}
return reward;
}
/** calculate the fee for quick withdrawal
*/
function calculateFee(uint256 v) constant returns (uint256) {
uint256 feeRequired = v / (1 wei * 100);
return feeRequired;
}
/**
* Quick withdrawal, needs to send ether to this function for the fee.
*
* Gas use: 44129 (including call to processWithdrawal)
*/
function quickWithdraw() payable notPendingWithdrawal returns (bool) {
// calculate required fee
uint256 amount = balanceOf[msg.sender];
if (amount <= 0) throw;
uint256 feeRequired = calculateFee(amount);
if (msg.value < feeRequired) {
// not enough fees sent
InsufficientFee(msg.sender, feeRequired);
return false;
}
uint256 overAmount = msg.value - feeRequired; // calculate any over-payment
// add fee to the feePot, excluding any over-payment
if (overAmount > 0) {
feePot += msg.value - overAmount;
} else {
feePot += msg.value;
}
doWithdrawal(overAmount); // withdraw + return any over payment
WithdrawalDone(msg.sender, amount, 0);
return true;
}
/**
* do withdrawal
* Gas: 62483
*/
function doWithdrawal(uint256 extra) internal {
uint256 amount = balanceOf[msg.sender];
if (amount <= 0) throw; // cannot withdraw
balanceOf[msg.sender] = 0;
if (totalSupply > totalSupply - amount) {
totalSupply = 0; // don't let it overflow
} else {
totalSupply -= amount; // deflate the supply!
}
Transfer(msg.sender, 0, amount); // burn baby burn
if (!msg.sender.send(amount + extra)) throw; // return back the ether or rollback if failed
}
/**
* Fallback function when sending ether to the contract
* Gas use: 65051
*/
function () payable notPendingWithdrawal {
uint256 amount = msg.value; // amount that was sent
if (amount <= 0) throw; // need to send some ETH
balanceOf[msg.sender] += amount; // mint new tokens
totalSupply += amount; // track the supply
Transfer(0, msg.sender, amount); // notify of the event
Deposited(msg.sender, amount);
}
} | Reward is based on the amount held, relative to total supply of tokens./ | function calculateReward(uint256 v) constant returns (uint256) {
uint256 reward = 0;
if (feePot > 0) {
reward = v / totalSupply * feePot;
}
return reward;
}
| 7,273,971 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IMultiVaultStrategy {
function want() external view returns (address);
function deposit() external;
function withdraw(address _asset) external;
function withdraw(uint _amount) external returns (uint);
function withdrawToController(uint _amount) external;
function skim() external;
function harvest(address _mergedStrategy) external;
function withdrawAll() external returns (uint);
function balanceOf() external view returns (uint);
function withdrawFee(uint) external view returns (uint); // pJar: 0.5% (50/10000)
}
interface IValueMultiVault {
function cap() external view returns (uint);
function getConverter(address _want) external view returns (address);
function getVaultMaster() external view returns (address);
function balance() external view returns (uint);
function token() external view returns (address);
function available(address _want) external view returns (uint);
function accept(address _input) external view returns (bool);
function claimInsurance() external;
function earn(address _want) external;
function harvest(address reserve, uint amount) external;
function withdraw_fee(uint _shares) external view returns (uint);
function calc_token_amount_deposit(uint[] calldata _amounts) external view returns (uint);
function calc_token_amount_withdraw(uint _shares, address _output) external view returns (uint);
function convert_rate(address _input, uint _amount) external view returns (uint);
function getPricePerFullShare() external view returns (uint);
function get_virtual_price() external view returns (uint); // average dollar value of vault share token
function deposit(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount);
function depositFor(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount);
function depositAll(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount);
function depositAllFor(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount);
function withdraw(uint _shares, address _output, uint _min_output_amount) external returns (uint);
function withdrawFor(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount);
function harvestStrategy(address _strategy) external;
function harvestWant(address _want) external;
function harvestAllStrategies() external;
}
interface IShareConverter {
function convert_shares_rate(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount);
function convert_shares(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount);
}
interface Converter {
function convert(address) external returns (uint);
}
contract MultiStablesVaultController {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
address public strategist;
struct StrategyInfo {
address strategy;
uint quota; // set = 0 to disable
uint percent;
}
IValueMultiVault public vault;
address public basedWant;
address[] public wantTokens; // sorted by preference
// want => quota, length
mapping(address => uint) public wantQuota;
mapping(address => uint) public wantStrategyLength;
// want => stratId => StrategyInfo
mapping(address => mapping(uint => StrategyInfo)) public strategies;
mapping(address => mapping(address => bool)) public approvedStrategies;
mapping(address => bool) public investDisabled;
IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...)
address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array
constructor(IValueMultiVault _vault) public {
require(address(_vault) != address(0), "!_vault");
vault = _vault;
basedWant = vault.token();
governance = msg.sender;
strategist = msg.sender;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function approveStrategy(address _want, address _strategy) external {
require(msg.sender == governance, "!governance");
approvedStrategies[_want][_strategy] = true;
}
function revokeStrategy(address _want, address _strategy) external {
require(msg.sender == governance, "!governance");
approvedStrategies[_want][_strategy] = false;
}
function setWantQuota(address _want, uint _quota) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
wantQuota[_want] = _quota;
}
function setWantStrategyLength(address _want, uint _length) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
wantStrategyLength[_want] = _length;
}
// want => stratId => StrategyInfo
function setStrategyInfo(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
require(approvedStrategies[_want][_strategy], "!approved");
strategies[_want][_sid].strategy = _strategy;
strategies[_want][_sid].quota = _quota;
strategies[_want][_sid].percent = _percent;
}
function setShareConverter(IShareConverter _shareConverter) external {
require(msg.sender == governance, "!governance");
shareConverter = _shareConverter;
}
function setInvestDisabled(address _want, bool _investDisabled) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
investDisabled[_want] = _investDisabled;
}
function setWantTokens(address[] memory _wantTokens) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
delete wantTokens;
uint _wlength = _wantTokens.length;
for (uint i = 0; i < _wlength; ++i) {
wantTokens.push(_wantTokens[i]);
}
}
function getStrategyCount() external view returns(uint _strategyCount) {
_strategyCount = 0;
uint _wlength = wantTokens.length;
for (uint i = 0; i < _wlength; i++) {
_strategyCount = _strategyCount.add(wantStrategyLength[wantTokens[i]]);
}
}
function wantLength() external view returns (uint) {
return wantTokens.length;
}
function wantStrategyBalance(address _want) public view returns (uint) {
uint _bal = 0;
for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) {
_bal = _bal.add(IMultiVaultStrategy(strategies[_want][_sid].strategy).balanceOf());
}
return _bal;
}
function want() external view returns (address) {
if (lazySelectedBestStrategy != address(0)) {
return IMultiVaultStrategy(lazySelectedBestStrategy).want();
}
uint _wlength = wantTokens.length;
if (_wlength > 0) {
if (_wlength == 1) {
return wantTokens[0];
}
for (uint i = 0; i < _wlength; i++) {
address _want = wantTokens[i];
uint _bal = wantStrategyBalance(_want);
if (_bal < wantQuota[_want]) {
return _want;
}
}
}
return basedWant;
}
function setLazySelectedBestStrategy(address _strategy) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
lazySelectedBestStrategy = _strategy;
}
function getBestStrategy(address _want) public view returns (address _strategy) {
if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).want() == _want) {
return lazySelectedBestStrategy;
}
uint _wantStrategyLength = wantStrategyLength[_want];
_strategy = address(0);
if (_wantStrategyLength == 0) return _strategy;
uint _totalBal = wantStrategyBalance(_want);
if (_totalBal == 0) {
// first depositor, simply return the first strategy
return strategies[_want][0].strategy;
}
uint _bestDiff = 201;
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
uint _stratBal = IMultiVaultStrategy(sinfo.strategy).balanceOf();
if (_stratBal < sinfo.quota) {
uint _diff = _stratBal.add(_totalBal).mul(100).div(_totalBal).sub(sinfo.percent); // [100, 200] - [percent]
if (_diff < _bestDiff) {
_bestDiff = _diff;
_strategy = sinfo.strategy;
}
}
}
if (_strategy == address(0)) {
_strategy = strategies[_want][0].strategy;
}
}
function earn(address _token, uint _amount) external {
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist");
address _strategy = getBestStrategy(_token);
if (_strategy == address(0) || IMultiVaultStrategy(_strategy).want() != _token) {
// forward to vault and then call earnExtra() by its governance
IERC20(_token).safeTransfer(address(vault), _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
IMultiVaultStrategy(_strategy).deposit();
}
}
function withdraw_fee(address _want, uint _amount) external view returns (uint) {
address _strategy = getBestStrategy(_want);
return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).withdrawFee(_amount);
}
function balanceOf(address _want, bool _sell) external view returns (uint _totalBal) {
uint _wlength = wantTokens.length;
if (_wlength == 0) {
return 0;
}
_totalBal = 0;
for (uint i = 0; i < _wlength; i++) {
address wt = wantTokens[i];
uint _bal = wantStrategyBalance(wt);
if (wt != _want) {
_bal = shareConverter.convert_shares_rate(wt, _want, _bal);
if (_sell) {
_bal = _bal.mul(9998).div(10000); // minus 0.02% for selling
}
}
_totalBal = _totalBal.add(_bal);
}
}
function withdrawAll(address _strategy) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
// WithdrawAll sends 'want' to 'vault'
IMultiVaultStrategy(_strategy).withdrawAll();
}
function inCaseTokensGetStuck(address _token, uint _amount) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IERC20(_token).safeTransfer(address(vault), _amount);
}
function inCaseStrategyGetStuck(address _strategy, address _token) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IMultiVaultStrategy(_strategy).withdraw(_token);
IERC20(_token).safeTransfer(address(vault), IERC20(_token).balanceOf(address(this)));
}
function claimInsurance() external {
require(msg.sender == governance, "!governance");
vault.claimInsurance();
}
// note that some strategies do not allow controller to harvest
function harvestStrategy(address _strategy) external {
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
IMultiVaultStrategy(_strategy).harvest(address(0));
}
function harvestWant(address _want) external {
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
uint _wantStrategyLength = wantStrategyLength[_want];
address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
if (_firstStrategy == address(0)) {
_firstStrategy = sinfo.strategy;
} else {
IMultiVaultStrategy(sinfo.strategy).harvest(_firstStrategy);
}
}
if (_firstStrategy != address(0)) {
IMultiVaultStrategy(_firstStrategy).harvest(address(0));
}
}
function harvestAllStrategies() external {
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
uint _wlength = wantTokens.length;
address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here
for (uint i = 0; i < _wlength; i++) {
address _want = wantTokens[i];
uint _wantStrategyLength = wantStrategyLength[_want];
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
if (_firstStrategy == address(0)) {
_firstStrategy = sinfo.strategy;
} else {
IMultiVaultStrategy(sinfo.strategy).harvest(_firstStrategy);
}
}
}
if (_firstStrategy != address(0)) {
IMultiVaultStrategy(_firstStrategy).harvest(address(0));
}
}
function switchFund(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
_srcStrat.withdrawToController(_amount);
address _srcWant = _srcStrat.want();
address _destWant = _destStrat.want();
if (_srcWant != _destWant) {
_amount = IERC20(_srcWant).balanceOf(address(this));
require(shareConverter.convert_shares_rate(_srcWant, _destWant, _amount) > 0, "rate=0");
IERC20(_srcWant).safeTransfer(address(shareConverter), _amount);
shareConverter.convert_shares(_srcWant, _destWant, _amount);
}
IERC20(_destWant).safeTransfer(address(_destStrat), IERC20(_destWant).balanceOf(address(this)));
_destStrat.deposit();
}
function withdraw(address _want, uint _amount) external returns (uint _withdrawFee) {
require(msg.sender == address(vault), "!vault");
_withdrawFee = 0;
uint _toWithdraw = _amount;
uint _wantStrategyLength = wantStrategyLength[_want];
uint _received;
for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) {
StrategyInfo storage sinfo = strategies[_want][_sid - 1];
IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy);
uint _stratBal = _strategy.balanceOf();
if (_toWithdraw < _stratBal) {
_received = _strategy.withdraw(_toWithdraw);
_withdrawFee = _withdrawFee.add(_strategy.withdrawFee(_received));
return _withdrawFee;
}
_received = _strategy.withdrawAll();
_withdrawFee = _withdrawFee.add(_strategy.withdrawFee(_received));
if (_received >= _toWithdraw) {
return _withdrawFee;
}
_toWithdraw = _toWithdraw.sub(_received);
}
if (_toWithdraw > 0) {
// still not enough, try to withdraw from other wants strategies
uint _wlength = wantTokens.length;
for (uint i = _wlength; i > 0; i--) {
address wt = wantTokens[i - 1];
if (wt != _want) {
(uint _wamt, uint _wdfee) = _withdrawOtherWant(_want, wt, _toWithdraw);
_withdrawFee = _withdrawFee.add(_wdfee);
if (_wamt >= _toWithdraw) {
return _withdrawFee;
}
_toWithdraw = _toWithdraw.sub(_wamt);
}
}
}
return _withdrawFee;
}
function _withdrawOtherWant(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) {
// Check balance
uint b = IERC20(_want).balanceOf(address(this));
_withdrawFee = 0;
if (b >= _amount) {
_wantAmount = b;
} else {
uint _toWithdraw = _amount.sub(b);
uint _toWithdrawOther = _toWithdraw.mul(101).div(100); // add 1% extra
uint _otherBal = IERC20(_other).balanceOf(address(this));
if (_otherBal < _toWithdrawOther) {
uint _otherStrategyLength = wantStrategyLength[_other];
for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) {
StrategyInfo storage sinfo = strategies[_other][_sid - 1];
IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy);
uint _stratBal = _strategy.balanceOf();
uint _needed = _toWithdrawOther.sub(_otherBal);
uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal;
_strategy.withdrawToController(_wdamt);
_withdrawFee = _withdrawFee.add(_strategy.withdrawFee(_wdamt));
_otherBal = IERC20(_other).balanceOf(address(this));
if (_otherBal >= _toWithdrawOther) {
break;
}
}
}
IERC20(_other).safeTransfer(address(shareConverter), _otherBal);
shareConverter.convert_shares(_other, _want, _otherBal);
_wantAmount = IERC20(_want).balanceOf(address(this));
}
IERC20(_want).safeTransfer(address(vault), _wantAmount);
}
} | WithdrawAll sends 'want' to 'vault' | function withdrawAll(address _strategy) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IMultiVaultStrategy(_strategy).withdrawAll();
}
| 5,715,475 |
./full_match/80001/0xc217357dB83Edb0E6ECc45D59B8ebd4A11cb0Dec/sources/project_/contracts/Amberfi/Market.sol | Get auction IDs in an offset with index `offset_` for `length_` length offset_ (uint256) Offset index length_ (uint256) Length of an offset return auctionIds (uint256[] memory) Auction IDs return nextOffset (uint256) Next offset index/ | function getAuctions(uint256 offset_, uint256 length_)
external
view
returns (uint256[] memory auctionIds, uint256 nextOffset)
{
uint256 length = getAuctionsCount();
if (length_ > length - offset_) {
length_ = length - offset_;
}
auctionIds = new uint256[](length_);
for (uint256 i; i < length_; ++i) {
auctionIds[i] = _auctions[offset_ + i].auctionId;
}
nextOffset = offset_ + length_;
}
| 848,017 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <=0.7.3;
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
import { Lib_BytesUtils } from "./Lib_BytesUtils.sol";
import { Lib_RLPReader } from "./Lib_RLPReader.sol";
contract Optimistic_Rollups {
bytes32 public stateRoot;
bytes32 public prev_stateRoot;
address public last_batch_submitter;
uint256 public immutable lock_time;
uint256 public immutable required_bond;
uint256 public last_batch_time;
mapping(address => address) public aggregators;
mapping(bytes32 => bool) public valid_stateRoots;
mapping(address => mapping(bytes32 => uint256)) private last_deposits;
mapping(address => mapping(bytes32 => uint256)) private last_withdraws;
event New_Deposit(address user, bytes32 stateRoot, uint256 value);
event New_withdraw(address user, bytes32 stateRoot, uint256 value);
event Fraud_Proved(address challenger);
event Invalid_Proof(address challenger);
constructor(
uint256 _lock_time,
uint256 _required_bond
) public {
stateRoot = bytes32(0);
prev_stateRoot = bytes32(0);
lock_time = _lock_time;
last_batch_time = block.timestamp - _lock_time;
required_bond = _required_bond;
}
modifier is_aggregator(address user) {
require(aggregators[user] != address(0), "UNAUTHORIZED_ACCOUNT");
_;
}
modifier can_exit_optimism() {
// Check that enough time has elapsed for potential fraud proofs (10 minutes)
require (block.timestamp >= last_batch_time + lock_time, "OPTIMISTIC_PERIOD");
_;
}
modifier fraud_period() {
require (block.timestamp < last_batch_time + lock_time, "OPTIMISTIC_PERIOD");
_;
}
//Bonds msg.value for msg.sender to become and aggregator
function bond() external payable {
require(msg.value >= required_bond, "INSUFFICIENT_BOND");
aggregators[msg.sender] = msg.sender;
}
//Deposits funds so they can be used in layer2
function deposit() external payable can_exit_optimism() {
//we must verity stateRoot is valid
last_deposits[msg.sender][stateRoot] += msg.value;
emit New_Deposit(msg.sender, stateRoot, msg.value);
}
function withdraw(bytes calldata _key, bytes calldata _value, bytes memory _proof, bytes32 _root) external can_exit_optimism() {
require(_root == stateRoot, "NOT_VALID_PROOF");
//prevent double withdraw
require(last_withdraws[msg.sender][stateRoot] == 0, "WITHDRAW_ALREADY_DONE");
require(Lib_MerkleTrie.verifyInclusionProof(_key,_value,_proof,_root) == true, "INVALID_ACCOUNT_PROOF");
address accAddr = Lib_BytesUtils.toAddress(_key,0);
//Check msg.sender == proof address
require (accAddr == msg.sender, "INVALID_WITHDRAW_REQUESTER");
Lib_RLPReader.RLPItem[] memory account = Lib_RLPReader.readList(_value);
uint256 accBalance = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[1]));
last_withdraws[msg.sender][stateRoot] += accBalance;
msg.sender.transfer(accBalance);
emit New_withdraw(msg.sender, stateRoot, accBalance);
}
//[248, 95, 160, 48, 90, 96, 180, 15, 169, 0, 12, 30, 160, 135, 133, 84, 61, 18, 113, 22, 62, 245, 86, 20, 148, 103, 136, 32, 124, 139, 204, 83, 60, 79, 110, 248, 60, 248, 58, 136, 13, 224, 182, 179, 167, 100, 0, 0, 133, 11, 164, 59, 116, 0, 148, 139, 80, 60, 161, 190, 245, 90, 144, 66, 118, 19, 143, 46, 166, 9, 6, 210, 197, 135, 129, 148, 4, 140, 130, 254, 44, 133, 149, 108, 242, 135, 47, 190, 50, 190, 74, 208, 109, 227, 219, 30, 1]
function newBatch(bytes calldata _batch) external is_aggregator(msg.sender) can_exit_optimism() returns (string memory) {
//here we should check if fraud proof time has expired
require(_batch.length > 0, "EMPTY_NEW_BATCH");
Lib_RLPReader.RLPItem[] memory ls = Lib_RLPReader.readList(_batch);
Lib_RLPReader.RLPItem memory _stateRoot = ls[0];
require(stateRoot == abi.decode(Lib_RLPReader.readBytes(_stateRoot), (bytes32)), "INVALID_PREV_STATEROOT");
prev_stateRoot = stateRoot;
Lib_RLPReader.RLPItem memory _newstateRoot = ls[1];
stateRoot = abi.decode(Lib_RLPReader.readBytes(_newstateRoot), (bytes32));
//At this point we consider the prevBatch as correct
valid_stateRoots[prev_stateRoot] = true;
last_batch_submitter = msg.sender;
last_batch_time = block.timestamp;
}
//account_proof must contain a proof of the account balance for the previous stateRoot
function prove_fraud(bytes calldata _key, bytes calldata _value, bytes memory _proof, bytes32 _root, bytes calldata _lastBatch) external fraud_period() {
//Check proof
require(_root == prev_stateRoot && stateRoot != prev_stateRoot, "NOT_VALID_PROOF");
require(Lib_MerkleTrie.verifyInclusionProof(_key,_value,_proof,_root) == true, "INVALID_ACCOUNT_PROOF");
//Extractic account values
//Research what costs more: keccak256 or toAddress(_key)
bytes32 accAddr = keccak256(_key); //we will compare with the hash of the bytes representing the account
Lib_RLPReader.RLPItem[] memory account = Lib_RLPReader.readList(_value);
uint256 accBalance = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[1]));
//uint256 accNonce = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[0]));
//We must increment and decrease account balance with its last deposits/withdraws as are not contemplated in the account proof
accBalance += last_deposits[Lib_BytesUtils.toAddress(_key,0)][prev_stateRoot];
accBalance -= last_withdraws[Lib_BytesUtils.toAddress(_key,0)][prev_stateRoot];
//Now we must verify the value of the account after the applyed batch
Lib_RLPReader.RLPItem[] memory ls = Lib_RLPReader.readList(_lastBatch);
Lib_RLPReader.RLPItem[] memory transactions = Lib_RLPReader.readList(ls[2]);
for (uint256 i = 0; i < transactions.length; i++) {
Lib_RLPReader.RLPItem[] memory tx_data = Lib_RLPReader.readList(transactions[i]);
//if is the receipent
if (keccak256(Lib_RLPReader.readBytes(tx_data[2])) == accAddr) {
accBalance += Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(tx_data[1]));
} else if (keccak256(Lib_RLPReader.readBytes(tx_data[3])) == accAddr) {
uint256 txValue = abi.decode(Lib_RLPReader.readBytes(tx_data[1]), (uint256));
if (txValue > accBalance) {
emit Fraud_Proved(msg.sender);
delete aggregators[last_batch_submitter];
stateRoot = prev_stateRoot;
msg.sender.transfer(required_bond);
return;
}
accBalance -= txValue;
}
}
emit Invalid_Proof(msg.sender);
//if fraud is proved => change to the last apporved stateRoot and reward the prover
}
function remaining_proof_time() view public returns (uint256) {
uint256 remaining = (last_batch_time + lock_time) - block.timestamp;
if (remaining < 0) return 0;
return remaining;
}
}
| Deposits funds so they can be used in layer2we must verity stateRoot is valid | function deposit() external payable can_exit_optimism() {
last_deposits[msg.sender][stateRoot] += msg.value;
emit New_Deposit(msg.sender, stateRoot, msg.value);
}
| 1,767,023 |
./full_match/56/0x1C5C0E1B96E7ADDC14AED3688E547A6103A244d9/sources/project_/contracts/Router1.sol | Set whether anti-whale is enabled. e Whether anti-whale is enabled./ Update whether anti-whale is enabled. | function setAntiWhaleEnabled(bool e) external onlyOwner {
_isAntiWhaleEnabled = e;
}
| 3,227,267 |
pragma solidity 0.4.24;
import "./Authorizable.sol";
import "./EightExToken.sol";
import "./base/math/SafeMath.sol";
/** @title Stake Contract - Processors stake tokens to claim transactions */
/** @author Kerman Kohli - <[email protected]> */
contract StakeContract is Authorizable {
using SafeMath for uint;
struct Stake {
uint lockedUp;
uint total;
}
struct TokenStake {
uint lockedUp;
uint total;
}
mapping (address => mapping (address => Stake)) public userStakes;
mapping (address => TokenStake) tokenStakes;
EightExToken public tokenContract;
event Locked(address indexed staker, address indexed tokenAddress, uint indexed amount);
event Unlocked(address indexed staker, address indexed tokenAddress, uint indexed amount);
event Slashed(address indexed staker, address indexed tokenAddress, uint indexed amount);
event Transferred(address indexed staker, address indexed tokenAddress, uint indexed amount, address destination);
event ToppedUp(address indexed staker, address indexed tokenAddress, uint indexed amount);
event Withdrew(address indexed staker, address indexed tokenAddress, uint indexed amount);
/**
* PUBLIC FUNCTIONS
*/
constructor(address _tokenAddress) public {
tokenContract = EightExToken(_tokenAddress);
}
/** @dev When the processor claims a transaction their tokens are staked.
* @param _staker is the processors who is staking thier tokens.
* @param _tokenAddress token for which to stake for.
* @param _amount is how much they would like to stake;
*/
function lockTokens(address _staker, address _tokenAddress, uint _amount)
public
onlyAuthorized
{
require(getAvailableStake(_staker, _tokenAddress) >= _amount);
userStakes[_staker][_tokenAddress].lockedUp += _amount;
tokenStakes[_tokenAddress].lockedUp += _amount;
emit Locked(_staker, _tokenAddress, _amount);
}
/** @dev When a processor executes a transaction their tokens are unstaked.
* @param _staker is the processors who is staking thier tokens.
* @param _tokenAddress token for which to stake for.
* @param _amount is how much they would like to unstake;
*/
function unlockTokens(address _staker, address _tokenAddress, uint _amount)
public
onlyAuthorized
{
// Ensure that they can't unstake more than they actually have
require(userStakes[_staker][_tokenAddress].lockedUp >= _amount);
userStakes[_staker][_tokenAddress].lockedUp -= _amount;
tokenStakes[_tokenAddress].lockedUp -= _amount;
emit Unlocked(_staker, _tokenAddress, _amount);
}
/** @dev When the processor doesn't execute a transaction they claimed
* their tokens are slashed.
* @param _staker is the processors who's tokens need to be slashed.
* @param _tokenAddress token for which to stake for.
* @param _amount is how many tokens need to be slashed.
*/
function slashTokens(address _staker, address _tokenAddress, uint _amount)
public
onlyAuthorized
{
// Make sure that an authorized address can't slash more tokens than
// they actually have locked up.
require(userStakes[_staker][_tokenAddress].lockedUp >= _amount);
// Reduce the total amount first
userStakes[_staker][_tokenAddress].total -= _amount;
userStakes[_staker][_tokenAddress].lockedUp -= _amount;
tokenStakes[_tokenAddress].total -= _amount;
tokenStakes[_tokenAddress].lockedUp -= _amount;
emit Slashed(_staker, _tokenAddress, _amount);
}
/** @dev When someone catches out another user for not processing
* their tokens are transferred to them.
* @param _staker is the processors who's tokens need to be slashed.
* @param _tokenAddress token for which to stake for.
* @param _amount is how many tokens need to be slashed.
* @param _destination is the person to transfer the stake to.
*/
function transferStake(address _staker, address _tokenAddress, uint _amount, address _destination)
public
onlyAuthorized
{
// Make sure that an authorized address can't slash more tokens than
// they actually have locked up.
require(userStakes[_staker][_tokenAddress].lockedUp >= _amount);
// Reduce the total amount first
userStakes[_staker][_tokenAddress].total -= _amount;
userStakes[_staker][_tokenAddress].lockedUp -= _amount;
// Transfer the stake
userStakes[_destination][_tokenAddress].total += _amount;
tokenStakes[_tokenAddress].lockedUp -= _amount; // Total is constant, only locked up decreases.
emit Transferred(_staker, _tokenAddress, _amount, _destination);
}
/** @dev Check how many tokens the processor has in total at this moment.
* @param _staker is the processor address.
* @param _tokenAddress token for which to stake for.
*/
function getTotalStake(address _staker, address _tokenAddress)
public
view
returns (uint total)
{
return userStakes[_staker][_tokenAddress].total;
}
/** @dev Check how many tokens the processor has available at this moment.
* @param _staker is the processor address.
* @param _tokenAddress token for which to stake for.
*/
function getAvailableStake(address _staker, address _tokenAddress)
public
view
returns (uint available)
{
return (userStakes[_staker][_tokenAddress].total - userStakes[_staker][_tokenAddress].lockedUp);
}
/** @dev Check how many tokens the processor has locked at this moment.
* @param _staker is the processor address.
* @param _tokenAddress token for which to stake for.
*/
function getLockedStake(address _staker, address _tokenAddress)
public
view
returns (uint locked)
{
return userStakes[_staker][_tokenAddress].lockedUp;
}
/** @dev Check how many staked tokens the currency has in total at this moment.
* @param _tokenAddress token for which to stake for.
*/
function getTotalTokenStake(address _tokenAddress)
public
view
returns (uint total)
{
return tokenStakes[_tokenAddress].total;
}
/** @dev Check how many tokens the currency has available at this moment.
* @param _tokenAddress token for which to stake for.
*/
function getAvailableTokenStake(address _tokenAddress)
public
view
returns (uint available)
{
return (tokenStakes[_tokenAddress].total - tokenStakes[_tokenAddress].lockedUp);
}
/** @dev Check how many tokens the currency has locked at this moment.
* @param _tokenAddress token for which to stake for.
*/
function getLockedTokenStake(address _tokenAddress)
public
view
returns (uint locked)
{
return tokenStakes[_tokenAddress].lockedUp;
}
/** @dev Top up your stake once you've given approval to transfer funds.
* @param _amount is how much you would like to withdraw.
* @param _tokenAddress token for which to stake for.
*/
function topUpStake(uint _amount, address _tokenAddress)
public
returns (bool success)
{
if (tokenContract.transferFrom(msg.sender, address(this), _amount)) {
userStakes[msg.sender][_tokenAddress].total += _amount;
tokenStakes[_tokenAddress].total += _amount;
return true;
} else {
return false;
}
emit ToppedUp(msg.sender, _tokenAddress, _amount);
}
/** @dev Withdraw your stake from the stake contract.
* @param _amount is how much you would like to withdraw.
* @param _tokenAddress token for which to stake for.
*/
function withdrawStake(uint _amount, address _tokenAddress)
public
{
// Check that they're not taking out more than they actually have.
require(getAvailableStake(msg.sender, _tokenAddress) >= _amount);
userStakes[msg.sender][_tokenAddress].total -= _amount;
tokenStakes[_tokenAddress].total -= _amount;
tokenContract.transfer(msg.sender, _amount);
emit Withdrew(msg.sender, _tokenAddress, _amount);
}
} | Check how many tokens the processor has in total at this moment. _staker is the processor address. _tokenAddress token for which to stake for./ | function getTotalStake(address _staker, address _tokenAddress)
public
view
returns (uint total)
{
return userStakes[_staker][_tokenAddress].total;
}
| 7,328,121 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there are a number of accounts (the admins) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the starting admin of the contract. This
* can later be changed with {addAdmin and removeAdmin}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyAdmin`, which can be applied to your functions to restrict their use to
* the Admin.
*/
abstract contract AdminMod is Ownable {
mapping(address => bool) private _admins;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_addAdmin(owner());
}
/**
* @dev Returns the address of the current owner.
*/
function isAdmin(address addressForTesting)
public
view
virtual
onlyAdmin
returns (bool admin)
{
return _admins[addressForTesting];
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(_admins[msg.sender], "AdminMod: caller is not an admin");
_;
}
function addAdmin(address newAdmin) public virtual onlyAdmin {
require(!_admins[newAdmin], "Address is already a admin.");
_addAdmin(newAdmin);
}
function _addAdmin(address newAdmin) internal virtual {
_admins[newAdmin] = true;
}
function removeAdmin(address adminToRemove) public virtual onlyAdmin {
require(_admins[adminToRemove], "Adress is not an admin.");
require(adminToRemove!=owner(), "The owner has to be an admin.");
delete _admins[adminToRemove];
}
//newOwner will be declared as an admin
function transferOwnership(address newOwner) public virtual override onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_addAdmin(newOwner);
_transferOwnership(newOwner);
}
}
| Returns the address of the current owner./ | function isAdmin(address addressForTesting)
public
view
virtual
onlyAdmin
returns (bool admin)
{
return _admins[addressForTesting];
}
| 5,517,981 |
./partial_match/56/0xDD99f4e7a32B9e289352D9f20C5a0e8c0c4edbFB/sources/uTradeCompounder.sol | 0x0e430629 <- add liq0x48ccbc2e | interface uTrade {
function Buy(address who) payable external;
function Sell(uint256 _tokensSold) external;
function balanceOf(address account) external view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) external returns(bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
| 11,228,865 |
./partial_match/80001/0xD37583FC57dA40A5fA8d33Ce9ab13C430E39DBBA/sources/ERC721CollectionV2.sol | Set whether the collection can be editable or not. This property is used off-chain to check whether the items of the collection can be updated or not _value - Value to set/ | function setEditable(bool _value) external onlyOwner {
require(isEditable != _value, "BCV2#setEditable: VALUE_IS_THE_SAME");
emit SetEditable(isEditable, _value);
isEditable = _value;
}
| 8,819,550 |
./full_match/3/0xdd827aBd4d6312EF53d98cc159F8A34C5B480A07/sources/contracts/Pinu.sol | Returns the final amount for the tax.important This function only works with values based on token supply and NOT reflection supply./ | function _calculateTax(uint256 amount) private view returns (uint256) {
return _calculateFee(amount, taxFee);
}
| 14,201,101 |
./full_match/11155111/0x0E025D35eD0E243B8939924E7805f345495B9dF4/sources/project:/contracts/tokenLogic/TokenLogic.sol | 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./ Calculate the burning fees Overflow not possible: amount <= accountBalance <= totalSupply. | 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");
uint256 fee;
if(_mintAndBurnFee == 0){
fee = 0;
fee = amount / _mintAndBurnFee;
}
unchecked {
_balances[_feeAddress] += fee;
_balances[account] = accountBalance - amount;
_totalSupply -= (amount - fee);
}
emit Transfer(account, address(0), amount - fee);
emit Transfer(account, _feeAddress, fee);
_afterTokenTransfer(account, address(0), amount);
}
| 3,807,985 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@chainlink/[email protected]/src/v0.8/interfaces/LinkTokenInterface.sol";
import "@chainlink/[email protected]/src/v0.8/VRFRequestIDBase.sol";
import "@chainlink/[email protected]/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/[email protected]/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/[email protected]/access/Ownable.sol";
import "@openzeppelin/[email protected]/security/ReentrancyGuard.sol";
import "base64-sol/base64.sol";
contract Chainrand is VRFConsumerBase, ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint;
/// @dev This is the max uint that can be safely represented in JS double.
uint public MAX_TOKENS = 9007199254740991;
mapping(bytes32 => uint) internal vrfs;
/// @dev Metadata struct for token
struct Token {
string name; // fixed upon mint
string codeURI; // fixed upon mint
string seedKey;
string imageURI;
string projectURI;
address minter; // fixed upon mint
uint seedKeyHash; // fixed upon mint
uint codeHash; // fixed upon mint
uint randomness; // fixed upon mint (upon VRF fufilled)
uint paid;
bool verified;
}
/// @dev Metadata of tokens
mapping(uint => Token) public tokens;
/// @dev Nominal minimum mint fee.
uint public mintFee;
bytes32 internal vrfkeyHash;
uint public vrfFee;
event Verified(uint _tokenId);
event VerificationRevoked(uint _tokenId);
event RandomnessFufilled(uint _tokenId);
event SeedKeyRevealed(uint _tokenId);
event Paid(uint _tokenId);
// Get the values to connect to Chainlink from
// https://docs.chain.link/docs/vrf-contracts/
//
// Ethereum Mainnet
// ----------------
// LINK Token: 0x514910771AF9Ca656af840dff83E8264EcF986CA
// VRF Coordinator: 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952
// Key Hash: 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445
// Fee: 2
//
// Rinkeby Testnet
// ---------------
// LINK Token: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709
// VRF Coordinator: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B
// Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311
// Fee: 0.1
//
// Polygon Mainnet
// ---------------
// LINK Token: 0xb0897686c545045aFc77CF20eC7A532E3120E0F1
// VRF Coordinator: 0x3d2341ADb2D31f1c5530cDC622016af293177AE0
// Key Hash: 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da
// Fee: 0.0001
//
// Mumbai Testnet
// --------------
// LINK Token: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
// VRF Coordinator: 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
// Key Hash: 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4
// Fee: 0.0001
constructor()
ERC721("Chainrand", "RAND")
VRFConsumerBase(
0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, // VRF Coordinator
0x01BE23585060835E02B77ef475b0Cc51aA1e0709 // LINK Token
)
{
vrfkeyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
vrfFee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
}
/// @dev Mint a Chainrand token.
function mint(string memory _name, uint _seedKeyHash, uint _codeHash,
string memory _codeURI, string memory _imageURI, string memory _projectURI)
public payable nonReentrant {
require(LINK.transferFrom(msg.sender, address(this), vrfFee), "LINK payment failed.");
require(mintFee <= msg.value, "Insufficient payment.");
uint tokenId = totalSupply();
require(tokenId < MAX_TOKENS, "No more tokens available.");
_safeMint(msg.sender, tokenId);
tokens[tokenId] = Token(_name, _codeURI, "", _imageURI, _projectURI,
msg.sender, _seedKeyHash, _codeHash, 0, msg.value, false);
vrfs[requestRandomness(vrfkeyHash, vrfFee)] = tokenId;
}
// Callback function used by VRF Coordinator
function fulfillRandomness(bytes32 _requestId, uint _randomness) internal override {
uint tokenId = vrfs[_requestId];
tokens[tokenId].randomness = _randomness;
emit RandomnessFufilled(tokenId);
}
/// @dev For payments to support Chainrand.
function pay(uint _tokenId) public payable {
require(_tokenId < totalSupply(), "Token not found.");
tokens[_tokenId].paid += msg.value;
emit Paid(_tokenId);
}
/// @dev Sets the mint fee.
function setMintFee(uint _mintFee) public onlyOwner {
mintFee = _mintFee;
}
// Fake Mint.... for testing purposes.
function fakeMint(uint _count, string memory _name, uint _seedKeyHash, uint _codeHash,
string memory _codeURI, string memory _imageURI, string memory _projectURI)
public onlyOwner {
unchecked {
for (uint i = 0; i < _count; i++) {
uint tokenId = totalSupply();
_safeMint(msg.sender, tokenId);
uint randomness = uint(keccak256(abi.encodePacked(tokenId, msg.sender, blockhash(block.number - 1))));
tokens[tokenId] = Token(_name, _codeURI, "", _imageURI, _projectURI,
msg.sender, _seedKeyHash, _codeHash, randomness, 0, false);
emit RandomnessFufilled(tokenId);
}
}
}
/// @dev Withdraws Ether for the owner.
function withdraw() public onlyOwner {
uint256 amount = address(this).balance;
payable(msg.sender).transfer(amount);
}
/// @dev Change the token name.
function setSeedKey(uint _tokenId, string memory _seedKey) public {
require(ownerOf(_tokenId) == msg.sender, "You do not own this token.");
require(sha256(bytes(_seedKey)) == bytes32(tokens[_tokenId].seedKeyHash),
"Seed key hash does not match.");
tokens[_tokenId].seedKey = _seedKey;
emit SeedKeyRevealed(_tokenId);
}
/// @dev Change the token's image URI
function setImageURI(uint _tokenId, string memory _imageURI) public {
require(ownerOf(_tokenId) == msg.sender, "You do not own this token.");
tokens[_tokenId].imageURI = _imageURI;
}
/// @dev Change the token's project URI
function setProjectURI(uint _tokenId, string memory _projectURI) public {
require(ownerOf(_tokenId) == msg.sender, "You do not own this token.");
tokens[_tokenId].projectURI = _projectURI;
}
function escapeJsonString(string memory symbol) internal pure returns (string memory) {
unchecked {
bytes memory symbolBytes = bytes(symbol);
uint escapesLen = 0;
for (uint i = 0; i < symbolBytes.length; i++) {
uint b = uint(uint8(symbolBytes[i]));
if (b == 34 || b == 92 || b <= 31) {
escapesLen += 5;
}
}
bytes16 alphabet = "0123456789abcdef";
if (escapesLen > 0) {
bytes memory escapedBytes = new bytes(symbolBytes.length + escapesLen);
uint index;
for (uint i = 0; i < symbolBytes.length; i++) {
uint b = uint(uint8(symbolBytes[i]));
if (b == 34 || b == 92 || b <= 31) {
escapedBytes[index++] = '\\';
escapedBytes[index++] = 'u';
escapedBytes[index++] = '0';
escapedBytes[index++] = '0';
escapedBytes[index++] = alphabet[b >> 4];
escapedBytes[index++] = alphabet[b & 15];
} else {
escapedBytes[index++] = symbolBytes[i];
}
}
return string(escapedBytes);
}
return symbol;
}
}
function escapeCodeQuotes(string memory symbol) internal pure returns (string memory) {
unchecked {
bytes memory symbolBytes = bytes(symbol);
uint escapesLen = 0;
for (uint i = 0; i < symbolBytes.length; i++) {
uint b = uint(uint8(symbolBytes[i]));
if (b == 96) {
escapesLen += 1;
}
}
bytes memory escapedBytes = new bytes(symbolBytes.length + escapesLen);
uint index;
for (uint i = 0; i < symbolBytes.length; i++) {
uint b = uint(uint8(symbolBytes[i]));
if (b == 96) {
escapedBytes[index++] = '\\';
escapedBytes[index++] = '`';
} else {
escapedBytes[index++] = symbolBytes[i];
}
}
return string(escapedBytes);
}
}
function concat(string memory s0, string memory s1, string memory s2, string memory s3)
internal pure returns (string memory) {
unchecked { return string(abi.encodePacked(s0, s1, s2, s3)); }
}
function codeQuotes(string memory symbol) internal pure returns (string memory) {
unchecked { return concat('`', symbol, '`', ''); }
}
function addressToString(address _addr) internal pure returns(string memory) {
unchecked {
bytes32 value = bytes32(uint(uint160(_addr)));
bytes16 alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < 20; i++) {
uint b = uint(uint8(value[i + 12]));
uint j = 2+i*2;
str[j ] = alphabet[b >> 4];
str[j+1] = alphabet[b & 15];
}
return string(str);
}
}
/// @dev Returns the token URI in base64 data json.
function tokenURI(uint _tokenId) override public view returns (string memory) {
unchecked {
require(_tokenId < totalSupply(), "Token not found.");
Token memory t = tokens[_tokenId];
uint r = t.randomness;
string memory image;
if (bytes(t.imageURI).length == 0) {
for (uint i = 0; i < 32; i++) {
uint d = i & 7;
string memory x =
(d == 0) ? "<path d='M" :
(d == 2) ? "L" :
(d <= 3) ? " " :
(d == 4) ? "' style='stroke:rgba(" :
(d <= 6) ? "," : ",0.5);stroke-width:";
image = concat(image, x, (r & 255).toString(), (d == 7 ? "px'/>" : ""));
r >>= 8;
}
image = Base64.encode(abi.encodePacked(
"<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 256 256'>",
image, "</svg>"));
image = concat("data:image/svg+xml;base64,", image, '', '');
} else {
image = t.imageURI;
}
string memory a = concat(
'\\n\\nVerified: ', codeQuotes(t.verified ? "Yes" : "No"),
'\\n\\nMinter: ', codeQuotes(addressToString(t.minter))
);
if (bytes(t.projectURI).length > 0) {
a = concat(a, '\\n\\nProject URI: [Link](', escapeJsonString(t.projectURI),')');
}
if (bytes(t.codeURI).length > 0) {
a = concat(a, '\\n\\nCode URI: [Link](', escapeJsonString(t.codeURI),')');
}
a = concat(a, '\\n\\nCode Hash: ', codeQuotes(t.codeHash.toHexString()), '');
a = concat(a, '\\n\\nSeed Key Hash: ', codeQuotes(t.seedKeyHash.toHexString()), '');
if (bytes(t.seedKey).length > 0) {
a = concat(a, '\\n\\nSeed Key: ', codeQuotes(escapeCodeQuotes(t.seedKey)), '');
}
if (t.randomness > 0) {
a = concat(a, '\\n\\nRandomness: ', codeQuotes(t.randomness.toString()), '');
}
string memory json = Base64.encode(abi.encodePacked(
'{"name":"', t.name, '","description":"Provenance NFT for Chainlink VRF.',
a, '\\n","image":"', image, '"}'
));
return concat('data:application/json;base64,', json, '', '');
}
}
/// @dev Verify the token. Only callable by contract owner.
function verify(uint[] memory _tokenIds) public onlyOwner {
unchecked {
for (uint i = 0; i < _tokenIds.length; i++) {
uint tokenId = _tokenIds[i];
tokens[tokenId].verified = true;
emit Verified(tokenId);
}
}
}
/// @dev Revoke the verification. Only callable by contract owner.
function revokeVerification(uint[] memory _tokenIds) public onlyOwner {
unchecked {
for (uint i = 0; i < _tokenIds.length; i++) {
uint tokenId = _tokenIds[i];
tokens[tokenId].verified = false;
emit VerificationRevoked(tokenId);
}
}
}
/// @dev Returns the tokens' data in bulk.
function tokenData(uint[] memory _tokenIds) public view returns (string[] memory) {
unchecked {
uint tokenCount = 0;
uint numTokens = totalSupply();
for (uint i = 0; i < _tokenIds.length; i++) {
uint tokenId = _tokenIds[i];
if (tokenId < numTokens) {
tokenCount++;
}
}
string[] memory result = new string[](tokenCount * 12);
uint o = 0;
for (uint i = 0; i < tokenCount; i++) {
uint tokenId = _tokenIds[i];
if (tokenId < numTokens) {
Token memory t = tokens[tokenId];
result[o++] = tokenId.toString();
result[o++] = t.name;
result[o++] = t.codeURI;
result[o++] = t.seedKey;
result[o++] = t.imageURI;
result[o++] = t.projectURI;
result[o++] = addressToString(t.minter);
result[o++] = t.seedKeyHash.toHexString();
result[o++] = t.codeHash.toHexString();
result[o++] = t.randomness.toString();
result[o++] = t.paid.toString();
result[o++] = t.verified ? "1" : "0";
}
}
return result;
}
}
/// @dev Returns an array of the token ids under the owner.
function tokensOfOwner(address _owner) external view returns(uint[] memory) {
unchecked {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint[](0);
} else {
uint[] memory result = new uint[](tokenCount);
for (uint index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
}
} | Change the token's image URI | function setImageURI(uint _tokenId, string memory _imageURI) public {
require(ownerOf(_tokenId) == msg.sender, "You do not own this token.");
tokens[_tokenId].imageURI = _imageURI;
}
| 938,738 |
// SPDX-License-Identifier: MIT
// Telegram : https://t.me/sydnova_eth
pragma solidity 0.8.9;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
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;
}
}
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 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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @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);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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 {}
}
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;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
contract SYDNOVA is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("SYDNOVA", "SYD") {
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 = 5;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 5;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 8;
uint256 _earlySellDevFee = 7;
uint256 totalSupply = 5 * 1e8 * 1e18;
maxTransactionAmount = totalSupply * 5 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 10 / 1000; // 2% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet
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;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
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);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 20, "Must keep fees at 20% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 3) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("SYDNOVA", "SYD") {
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 = 5;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 5;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 8;
uint256 _earlySellDevFee = 7;
uint256 totalSupply = 5 * 1e8 * 1e18;
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);
| 6,284,297 |
pragma solidity ^0.4.23;
contract ToadFarmer {
uint256 public EGGS_TO_HATCH_1TOAD = 43200; // Half a day's worth of seconds to hatch
uint256 TADPOLE = 10000;
uint256 PSNHTOAD = 5000;
bool public initialized = false;
address public ceoAddress;
mapping (address => uint256) public hatcheryToad;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => address) public referrals;
uint256 public marketEggs;
constructor() public {
ceoAddress = msg.sender;
}
function hatchEggs(address ref) public {
require(initialized);
if (referrals[msg.sender] == 0 && referrals[msg.sender] != msg.sender) {
referrals[msg.sender] = ref;
}
uint256 eggsUsed = getMyEggs();
uint256 newToad = SafeMath.div(eggsUsed, EGGS_TO_HATCH_1TOAD);
hatcheryToad[msg.sender] = SafeMath.add(hatcheryToad[msg.sender], newToad);
claimedEggs[msg.sender] = 0;
lastHatch[msg.sender] = now;
// Send referral eggs
claimedEggs[referrals[msg.sender]] = SafeMath.add(claimedEggs[referrals[msg.sender]], SafeMath.div(eggsUsed, 5));
// Boost market to stop toad hoarding
marketEggs = SafeMath.add(marketEggs, SafeMath.div(eggsUsed, 10));
}
function sellEggs() public {
require(initialized);
uint256 hasEggs = getMyEggs();
uint256 eggValue = calculateEggSell(hasEggs);
uint256 fee = devFee(eggValue);
claimedEggs[msg.sender] = 0;
lastHatch[msg.sender] = now;
marketEggs = SafeMath.add(marketEggs, hasEggs);
ceoAddress.transfer(fee);
msg.sender.transfer(SafeMath.sub(eggValue, fee));
}
function buyEggs() public payable {
require(initialized);
uint256 eggsBought = calculateEggBuy(msg.value, SafeMath.sub(address(this).balance, msg.value));
eggsBought = SafeMath.sub(eggsBought, devFee(eggsBought));
claimedEggs[msg.sender] = SafeMath.add(claimedEggs[msg.sender], eggsBought);
ceoAddress.transfer(devFee(msg.value));
}
// Trade balancing algorithm
function calculateTrade(uint256 riggert, uint256 starboards, uint256 bigship) public view returns(uint256) {
// (TADPOLE*bigship) /
// (PSNHTOAD+((TADPOLE*starboards+PSNHTOAD*riggert)/riggert));
return SafeMath.div(SafeMath.mul(TADPOLE, bigship),
SafeMath.add(PSNHTOAD, SafeMath.div(SafeMath.add(SafeMath.mul(TADPOLE, starboards),SafeMath.mul(PSNHTOAD, riggert)), riggert)));
}
function calculateEggSell(uint256 eggs) public view returns(uint256) {
return calculateTrade(eggs, marketEggs, address(this).balance);
}
function calculateEggBuy(uint256 eth, uint256 contractBalance) public view returns(uint256) {
return calculateTrade(eth, contractBalance, marketEggs);
}
function calculateEggBuySimple(uint256 eth) public view returns(uint256) {
return calculateEggBuy(eth, address(this).balance);
}
function devFee(uint256 amount) public pure returns(uint256) {
return SafeMath.div(SafeMath.mul(amount, 4), 100);
}
function seedMarket(uint256 eggs) public payable {
require(marketEggs == 0);
initialized = true;
marketEggs = eggs;
}
function getFreeToad() public {
require(initialized);
require(hatcheryToad[msg.sender] == 0);
lastHatch[msg.sender] = now;
hatcheryToad[msg.sender] = uint(blockhash(block.number-1))%400 + 1; // 'Randomish' 1-400 free eggs
}
function getBalance() public view returns(uint256) {
return address(this).balance;
}
function getMyToad() public view returns(uint256) {
return hatcheryToad[msg.sender];
}
function getMyEggs() public view returns(uint256) {
return SafeMath.add(claimedEggs[msg.sender], getEggsSinceLastHatch(msg.sender));
}
function getEggsSinceLastHatch(address adr) public view returns(uint256) {
uint256 secondsPassed = min(EGGS_TO_HATCH_1TOAD, SafeMath.sub(now, lastHatch[adr]));
return SafeMath.mul(secondsPassed, hatcheryToad[adr]);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
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;
}
} | Trade balancing algorithm (TADPOLEbigship) / (PSNHTOAD+((TADPOLEstarboards+PSNHTOADriggert)/riggert)); | function calculateTrade(uint256 riggert, uint256 starboards, uint256 bigship) public view returns(uint256) {
return SafeMath.div(SafeMath.mul(TADPOLE, bigship),
SafeMath.add(PSNHTOAD, SafeMath.div(SafeMath.add(SafeMath.mul(TADPOLE, starboards),SafeMath.mul(PSNHTOAD, riggert)), riggert)));
}
| 2,429,932 |
pragma solidity ^0.5.0;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: contracts/assettoken/library/AssetTokenL.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title AssetTokenL library. */
library AssetTokenL {
using SafeMath for uint256;
///////////////////
// Struct Parameters (passed as parameter to library)
///////////////////
struct Supply {
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes. TransfersAndMints-index when the change
// occurred is also included
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Minting cap max amount of tokens
uint256 cap;
// When successfully funded
uint256 goal;
//crowdsale start
uint256 startTime;
//crowdsale end
uint256 endTime;
//crowdsale dividends
Dividend[] dividends;
//counter per address how much was claimed in continuous way
//note: counter also increases when recycled and tried to claim in continous way
mapping (address => uint256) dividendsClaimed;
uint256 tokenActionIndex; //only modify within library
}
struct Availability {
// Flag that determines if the token is yet alive.
// Meta data cannot be changed anymore (except capitalControl)
bool tokenAlive;
// Flag that determines if the token is transferable or not.
bool transfersEnabled;
// Flag that minting is finished
bool mintingPhaseFinished;
// Flag that minting is paused
bool mintingPaused;
}
struct Roles {
// role that can pause/resume
address pauseControl;
// role that can rescue accidentally sent tokens
address tokenRescueControl;
// role that can mint during crowdsale (usually controller)
address mintControl;
}
///////////////////
// Structs (saved to blockchain)
///////////////////
/// @dev `Dividend` is the structure that saves the status of a dividend distribution
struct Dividend {
uint256 currentTokenActionIndex;
uint256 timestamp;
DividendType dividendType;
address dividendToken;
uint256 amount;
uint256 claimedAmount;
uint256 totalSupply;
bool recycled;
mapping (address => bool) claimed;
}
/// @dev Dividends can be of those types.
enum DividendType { Ether, ERC20 }
/** @dev Checkpoint` is the structure that attaches a history index to a given value
* @notice That uint128 is used instead of uint/uint256. That's to save space. Should be big enough (feedback from audit)
*/
struct Checkpoint {
// `currentTokenActionIndex` is the index when the value was generated. It's uint128 to save storage space
uint128 currentTokenActionIndex;
// `value` is the amount of tokens at a specific index. It's uint128 to save storage space
uint128 value;
}
///////////////////
// Functions
///////////////////
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract. Check for availability must be done before.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(Supply storage _self, Availability storage /*_availability*/, address _from, address _to, uint256 _amount) public {
// Do not allow transfer to 0x0 or the token contract itself
require(_to != address(0), "addr0");
require(_to != address(this), "target self");
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint256 previousBalanceFrom = balanceOfNow(_self, _from);
require(previousBalanceFrom >= _amount, "not enough");
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(_self, _self.balances[_from], previousBalanceFrom.sub(_amount));
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfNow(_self, _to);
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
//info: don't move this line inside updateValueAtNow (because transfer is 2 actions)
increaseTokenActionIndex(_self);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
function increaseTokenActionIndex(Supply storage _self) private {
_self.tokenActionIndex = _self.tokenActionIndex.add(1);
emit TokenActionIndexIncreased(_self.tokenActionIndex, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` of his tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(Supply storage _self, address _spender, uint256 _amount) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (_self.allowed[msg.sender][_spender] == 0), "amount");
_self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @notice Increase the amount of tokens that an owner allowed to a spender.
/// @dev approve should be called when allowed[_spender] == 0. To increment
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
/// @return True if the approval was successful
function increaseApproval(Supply storage _self, address _spender, uint256 _addedValue) public returns (bool) {
_self.allowed[msg.sender][_spender] = _self.allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, _self.allowed[msg.sender][_spender]);
return true;
}
/// @notice Decrease the amount of tokens that an owner allowed to a spender.
/// @dev approve should be called when allowed[_spender] == 0. To decrement
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
/// @return True if the approval was successful
function decreaseApproval(Supply storage _self, address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = _self.allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
_self.allowed[msg.sender][_spender] = 0;
} else {
_self.allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _self.allowed[msg.sender][_spender]);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` if it is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(Supply storage _supply, Availability storage _availability, address _from, address _to, uint256 _amount)
public
returns (bool success)
{
// The standard ERC 20 transferFrom functionality
require(_supply.allowed[_from][msg.sender] >= _amount, "allowance");
_supply.allowed[_from][msg.sender] = _supply.allowed[_from][msg.sender].sub(_amount);
doTransfer(_supply, _availability, _from, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` WITHOUT approval. UseCase: notar transfers from lost wallet
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @param _fullAmountRequired Full amount required (causes revert if not).
/// @return True if the transfer was successful
function enforcedTransferFrom(
Supply storage _self,
Availability storage _availability,
address _from,
address _to,
uint256 _amount,
bool _fullAmountRequired)
public
returns (bool success)
{
if(_fullAmountRequired && _amount != balanceOfNow(_self, _from))
{
revert("Only full amount in case of lost wallet is allowed");
}
doTransfer(_self, _availability, _from, _to, _amount);
emit SelfApprovedTransfer(msg.sender, _from, _to, _amount);
return true;
}
////////////////
// Miniting
////////////////
/// @notice Function to mint tokens
/// @param _to The address that will receive the minted tokens.
/// @param _amount The amount of tokens to mint.
/// @return A boolean that indicates if the operation was successful.
function mint(Supply storage _self, address _to, uint256 _amount) public returns (bool) {
uint256 curTotalSupply = totalSupplyNow(_self);
uint256 previousBalanceTo = balanceOfNow(_self, _to);
// Check cap
require(curTotalSupply.add(_amount) <= _self.cap, "cap"); //leave inside library to never go over cap
// Check timeframe
require(_self.startTime <= now, "too soon");
require(_self.endTime >= now, "too late");
updateValueAtNow(_self, _self.totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
//info: don't move this line inside updateValueAtNow (because transfer is 2 actions)
increaseTokenActionIndex(_self);
emit MintDetailed(msg.sender, _to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at `_specificTransfersAndMintsIndex`
/// @param _owner The address from which the balance will be retrieved
/// @param _specificTransfersAndMintsIndex The balance at index
/// @return The balance at `_specificTransfersAndMintsIndex`
function balanceOfAt(Supply storage _self, address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256) {
return getValueAt(_self.balances[_owner], _specificTransfersAndMintsIndex);
}
function balanceOfNow(Supply storage _self, address _owner) public view returns (uint256) {
return getValueAt(_self.balances[_owner], _self.tokenActionIndex);
}
/// @dev Total amount of tokens at `_specificTransfersAndMintsIndex`.
/// @param _specificTransfersAndMintsIndex The totalSupply at index
/// @return The total amount of tokens at `_specificTransfersAndMintsIndex`
function totalSupplyAt(Supply storage _self, uint256 _specificTransfersAndMintsIndex) public view returns(uint256) {
return getValueAt(_self.totalSupplyHistory, _specificTransfersAndMintsIndex);
}
function totalSupplyNow(Supply storage _self) public view returns(uint256) {
return getValueAt(_self.totalSupplyHistory, _self.tokenActionIndex);
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given index
/// @param checkpoints The history of values being queried
/// @param _specificTransfersAndMintsIndex The index to retrieve the history checkpoint value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint256 _specificTransfersAndMintsIndex) private view returns (uint256) {
// requested before a check point was ever created for this token
if (checkpoints.length == 0 || checkpoints[0].currentTokenActionIndex > _specificTransfersAndMintsIndex) {
return 0;
}
// Shortcut for the actual value
if (_specificTransfersAndMintsIndex >= checkpoints[checkpoints.length-1].currentTokenActionIndex) {
return checkpoints[checkpoints.length-1].value;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1)/2;
if (checkpoints[mid].currentTokenActionIndex<=_specificTransfersAndMintsIndex) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Supply storage _self, Checkpoint[] storage checkpoints, uint256 _value) private {
require(_value == uint128(_value), "invalid cast1");
require(_self.tokenActionIndex == uint128(_self.tokenActionIndex), "invalid cast2");
checkpoints.push(Checkpoint(
uint128(_self.tokenActionIndex),
uint128(_value)
));
}
/// @dev Function to stop minting new tokens.
/// @return True if the operation was successful.
function finishMinting(Availability storage _self) public returns (bool) {
if(_self.mintingPhaseFinished) {
return false;
}
_self.mintingPhaseFinished = true;
emit MintFinished(msg.sender);
return true;
}
/// @notice Reopening crowdsale means minting is again possible. UseCase: notary approves and does that.
/// @return True if the operation was successful.
function reopenCrowdsale(Availability storage _self) public returns (bool) {
if(_self.mintingPhaseFinished == false) {
return false;
}
_self.mintingPhaseFinished = false;
emit Reopened(msg.sender);
return true;
}
/// @notice Set roles/operators.
/// @param _pauseControl pause control.
/// @param _tokenRescueControl token rescue control (accidentally assigned tokens).
function setRoles(Roles storage _self, address _pauseControl, address _tokenRescueControl) public {
require(_pauseControl != address(0), "addr0");
require(_tokenRescueControl != address(0), "addr0");
_self.pauseControl = _pauseControl;
_self.tokenRescueControl = _tokenRescueControl;
emit RolesChanged(msg.sender, _pauseControl, _tokenRescueControl);
}
/// @notice Set mint control.
function setMintControl(Roles storage _self, address _mintControl) public {
require(_mintControl != address(0), "addr0");
_self.mintControl = _mintControl;
emit MintControlChanged(msg.sender, _mintControl);
}
/// @notice Set token alive which can be seen as not in draft state anymore.
function setTokenAlive(Availability storage _self) public {
_self.tokenAlive = true;
}
////////////////
// Pausing token for unforeseen reasons
////////////////
/// @notice pause transfer.
/// @param _transfersEnabled True if transfers are allowed.
function pauseTransfer(Availability storage _self, bool _transfersEnabled) public
{
_self.transfersEnabled = _transfersEnabled;
if(_transfersEnabled) {
emit TransferResumed(msg.sender);
} else {
emit TransferPaused(msg.sender);
}
}
/// @notice calling this can enable/disable capital increase/decrease flag
/// @param _mintingEnabled True if minting is allowed
function pauseCapitalIncreaseOrDecrease(Availability storage _self, bool _mintingEnabled) public
{
_self.mintingPaused = (_mintingEnabled == false);
if(_mintingEnabled) {
emit MintingResumed(msg.sender);
} else {
emit MintingPaused(msg.sender);
}
}
/// @notice Receives ether to be distriubted to all token owners
function depositDividend(Supply storage _self, uint256 msgValue)
public
{
require(msgValue > 0, "amount0");
// gets the current number of total token distributed
uint256 currentSupply = totalSupplyNow(_self);
// a deposit without investment would end up in unclaimable deposit for token holders
require(currentSupply > 0, "0investors");
// creates a new index for the dividends
uint256 dividendIndex = _self.dividends.length;
// Stores the current meta data for the dividend payout
_self.dividends.push(
Dividend(
_self.tokenActionIndex, // current index used for claiming
block.timestamp, // Timestamp of the distribution
DividendType.Ether, // Type of dividends
address(0),
msgValue, // Total amount that has been distributed
0, // amount that has been claimed
currentSupply, // Total supply now
false // Already recylced
)
);
emit DividendDeposited(msg.sender, _self.tokenActionIndex, msgValue, currentSupply, dividendIndex);
}
/// @notice Receives ERC20 to be distriubted to all token owners
function depositERC20Dividend(Supply storage _self, address _dividendToken, uint256 _amount, address baseCurrency)
public
{
require(_amount > 0, "amount0");
require(_dividendToken == baseCurrency, "not baseCurrency");
// gets the current number of total token distributed
uint256 currentSupply = totalSupplyNow(_self);
// a deposit without investment would end up in unclaimable deposit for token holders
require(currentSupply > 0, "0investors");
// creates a new index for the dividends
uint256 dividendIndex = _self.dividends.length;
// Stores the current meta data for the dividend payout
_self.dividends.push(
Dividend(
_self.tokenActionIndex, // index that counts up on transfers and mints
block.timestamp, // Timestamp of the distribution
DividendType.ERC20,
_dividendToken,
_amount, // Total amount that has been distributed
0, // amount that has been claimed
currentSupply, // Total supply now
false // Already recylced
)
);
// it shouldn't return anything but according to ERC20 standard it could if badly implemented
// IMPORTANT: potentially a call with reentrance -> do at the end
require(ERC20(_dividendToken).transferFrom(msg.sender, address(this), _amount), "transferFrom");
emit DividendDeposited(msg.sender, _self.tokenActionIndex, _amount, currentSupply, dividendIndex);
}
/// @notice Function to claim dividends for msg.sender
/// @dev dividendsClaimed should not be handled here.
function claimDividend(Supply storage _self, uint256 _dividendIndex) public {
// Loads the details for the specific Dividend payment
Dividend storage dividend = _self.dividends[_dividendIndex];
// Devidends should not have been claimed already
require(dividend.claimed[msg.sender] == false, "claimed");
// Devidends should not have been recycled already
require(dividend.recycled == false, "recycled");
// get the token balance at the time of the dividend distribution
uint256 balance = balanceOfAt(_self, msg.sender, dividend.currentTokenActionIndex.sub(1));
// calculates the amount of dividends that can be claimed
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
// flag that dividends have been claimed
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
claimThis(dividend.dividendType, _dividendIndex, msg.sender, claim, dividend.dividendToken);
}
/// @notice Claim all dividends.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
function claimDividendAll(Supply storage _self) public {
claimLoopInternal(_self, _self.dividendsClaimed[msg.sender], (_self.dividends.length-1));
}
/// @notice Claim dividends in batches. In case claimDividendAll runs out of gas.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
/// @param _startIndex start index (inclusive number).
/// @param _endIndex end index (inclusive number).
function claimInBatches(Supply storage _self, uint256 _startIndex, uint256 _endIndex) public {
claimLoopInternal(_self, _startIndex, _endIndex);
}
/// @notice Claim loop of batch claim and claim all.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
/// @param _startIndex start index (inclusive number).
/// @param _endIndex end index (inclusive number).
function claimLoopInternal(Supply storage _self, uint256 _startIndex, uint256 _endIndex) private {
require(_startIndex <= _endIndex, "start after end");
//early exit if already claimed
require(_self.dividendsClaimed[msg.sender] < _self.dividends.length, "all claimed");
uint256 dividendsClaimedTemp = _self.dividendsClaimed[msg.sender];
// Cycle through all dividend distributions and make the payout
for (uint256 i = _startIndex; i <= _endIndex; i++) {
if (_self.dividends[i].recycled == true) {
//recycled and tried to claim in continuous way internally counts as claimed
dividendsClaimedTemp = SafeMath.add(i, 1);
}
else if (_self.dividends[i].claimed[msg.sender] == false) {
dividendsClaimedTemp = SafeMath.add(i, 1);
claimDividend(_self, i);
}
}
// This is done after the loop to reduce writes.
// Remembers what has been claimed after hole-free claiming procedure.
// IMPORTANT: do only if batch claim docks on previous claim to avoid unexpected claim all behaviour.
if(_startIndex <= _self.dividendsClaimed[msg.sender]) {
_self.dividendsClaimed[msg.sender] = dividendsClaimedTemp;
}
}
/// @notice Dividends which have not been claimed can be claimed by owner after timelock (to avoid loss)
/// @param _dividendIndex index of dividend to recycle.
/// @param _recycleLockedTimespan timespan required until possible.
/// @param _currentSupply current supply.
function recycleDividend(Supply storage _self, uint256 _dividendIndex, uint256 _recycleLockedTimespan, uint256 _currentSupply) public {
// Get the dividend distribution
Dividend storage dividend = _self.dividends[_dividendIndex];
// should not have been recycled already
require(dividend.recycled == false, "recycled");
// The recycle time has to be over
require(dividend.timestamp < SafeMath.sub(block.timestamp, _recycleLockedTimespan), "timeUp");
// Devidends should not have been claimed already
require(dividend.claimed[msg.sender] == false, "claimed");
//
//refund
//
// The amount, which has not been claimed is distributed to token owner
_self.dividends[_dividendIndex].recycled = true;
// calculates the amount of dividends that can be claimed
uint256 claim = SafeMath.sub(dividend.amount, dividend.claimedAmount);
// flag that dividends have been claimed
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
claimThis(dividend.dividendType, _dividendIndex, msg.sender, claim, dividend.dividendToken);
emit DividendRecycled(msg.sender, _self.tokenActionIndex, claim, _currentSupply, _dividendIndex);
}
/// @dev the core claim function of single dividend.
function claimThis(DividendType _dividendType, uint256 _dividendIndex, address payable _beneficiary, uint256 _claim, address _dividendToken)
private
{
// transfer the dividends to the token holder
if (_claim > 0) {
if (_dividendType == DividendType.Ether) {
_beneficiary.transfer(_claim);
}
else if (_dividendType == DividendType.ERC20) {
require(ERC20(_dividendToken).transfer(_beneficiary, _claim), "transfer");
}
else {
revert("unknown type");
}
emit DividendClaimed(_beneficiary, _dividendIndex, _claim);
}
}
/// @notice If this contract gets a balance in some other ERC20 contract - or even iself - then we can rescue it.
/// @param _foreignTokenAddress token where contract has balance.
/// @param _to the beneficiary.
function rescueToken(Availability storage _self, address _foreignTokenAddress, address _to) public
{
require(_self.mintingPhaseFinished, "unfinished");
ERC20(_foreignTokenAddress).transfer(_to, ERC20(_foreignTokenAddress).balanceOf(address(this)));
}
///////////////////
// Events (must be redundant in calling contract to work!)
///////////////////
event Transfer(address indexed from, address indexed to, uint256 value);
event SelfApprovedTransfer(address indexed initiator, address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event Approval(address indexed owner, address indexed spender, uint256 value);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event MintingPaused(address indexed initiator);
event MintingResumed(address indexed initiator);
event Reopened(address indexed initiator);
event DividendDeposited(address indexed depositor, uint256 transferAndMintIndex, uint256 amount, uint256 totalSupply, uint256 dividendIndex);
event DividendClaimed(address indexed claimer, uint256 dividendIndex, uint256 claim);
event DividendRecycled(address indexed recycler, uint256 transferAndMintIndex, uint256 amount, uint256 totalSupply, uint256 dividendIndex);
event RolesChanged(address indexed initiator, address pauseControl, address tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
event TokenActionIndexIncreased(uint256 tokenActionIndex, uint256 blocknumber);
}
// File: contracts/assettoken/interface/IBasicAssetToken.sol
interface IBasicAssetToken {
//AssetToken specific
function getLimits() external view returns (uint256, uint256, uint256, uint256);
function isTokenAlive() external view returns (bool);
function setMetaData(
string calldata _name,
string calldata _symbol,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external;
//Mintable
function mint(address _to, uint256 _amount) external returns (bool);
function finishMinting() external returns (bool);
//ERC20
function balanceOf(address _owner) external view returns (uint256 balance);
function approve(address _spender, uint256 _amount) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function totalSupply() external view returns (uint256);
function increaseApproval(address _spender, uint256 _addedValue) external returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue) external returns (bool);
function transfer(address _to, uint256 _amount) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success);
}
// File: contracts/assettoken/abstract/IBasicAssetTokenFull.sol
contract IBasicAssetTokenFull is IBasicAssetToken {
function checkCanSetMetadata() internal returns (bool);
function getCap() public view returns (uint256);
function getGoal() public view returns (uint256);
function getStart() public view returns (uint256);
function getEnd() public view returns (uint256);
function getLimits() public view returns (uint256, uint256, uint256, uint256);
function setMetaData(
string calldata _name,
string calldata _symbol,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external;
function getTokenRescueControl() public view returns (address);
function getPauseControl() public view returns (address);
function isTransfersPaused() public view returns (bool);
function setMintControl(address _mintControl) public;
function setRoles(address _pauseControl, address _tokenRescueControl) public;
function setTokenAlive() public;
function isTokenAlive() public view returns (bool);
function balanceOf(address _owner) public view returns (uint256 balance);
function approve(address _spender, uint256 _amount) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function totalSupply() public view returns (uint256);
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool);
function finishMinting() public returns (bool);
function rescueToken(address _foreignTokenAddress, address _to) public;
function balanceOfAt(address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256);
function totalSupplyAt(uint256 _specificTransfersAndMintsIndex) public view returns(uint256);
function enableTransfers(bool _transfersEnabled) public;
function pauseTransfer(bool _transfersEnabled) public;
function pauseCapitalIncreaseOrDecrease(bool _mintingEnabled) public;
function isMintingPaused() public view returns (bool);
function mint(address _to, uint256 _amount) public returns (bool);
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function enableTransferInternal(bool _transfersEnabled) internal;
function reopenCrowdsaleInternal() internal returns (bool);
function transferFromInternal(address _from, address _to, uint256 _amount) internal returns (bool success);
function enforcedTransferFromInternal(address _from, address _to, uint256 _value, bool _fullAmountRequired) internal returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event Reopened(address indexed initiator);
event MetaDataChanged(address indexed initiator, string name, string symbol, address baseCurrency, uint256 cap, uint256 goal);
event RolesChanged(address indexed initiator, address _pauseControl, address _tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
}
// File: contracts/assettoken/BasicAssetToken.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title Basic AssetToken. This contract includes the basic AssetToken features */
contract BasicAssetToken is IBasicAssetTokenFull, Ownable {
using SafeMath for uint256;
using AssetTokenL for AssetTokenL.Supply;
using AssetTokenL for AssetTokenL.Availability;
using AssetTokenL for AssetTokenL.Roles;
///////////////////
// Variables
///////////////////
string private _name;
string private _symbol;
// The token's name
function name() public view returns (string memory) {
return _name;
}
// Fixed number of 0 decimals like real world equity
function decimals() public pure returns (uint8) {
return 0;
}
// An identifier
function symbol() public view returns (string memory) {
return _symbol;
}
// 1000 is version 1
uint16 public constant version = 2000;
// Defines the baseCurrency of the token
address public baseCurrency;
// Supply: balance, checkpoints etc.
AssetTokenL.Supply supply;
// Availability: what's paused
AssetTokenL.Availability availability;
// Roles: who is entitled
AssetTokenL.Roles roles;
///////////////////
// Simple state getters
///////////////////
function isMintingPaused() public view returns (bool) {
return availability.mintingPaused;
}
function isMintingPhaseFinished() public view returns (bool) {
return availability.mintingPhaseFinished;
}
function getPauseControl() public view returns (address) {
return roles.pauseControl;
}
function getTokenRescueControl() public view returns (address) {
return roles.tokenRescueControl;
}
function getMintControl() public view returns (address) {
return roles.mintControl;
}
function isTransfersPaused() public view returns (bool) {
return !availability.transfersEnabled;
}
function isTokenAlive() public view returns (bool) {
return availability.tokenAlive;
}
function getCap() public view returns (uint256) {
return supply.cap;
}
function getGoal() public view returns (uint256) {
return supply.goal;
}
function getStart() public view returns (uint256) {
return supply.startTime;
}
function getEnd() public view returns (uint256) {
return supply.endTime;
}
function getLimits() public view returns (uint256, uint256, uint256, uint256) {
return (supply.cap, supply.goal, supply.startTime, supply.endTime);
}
function getCurrentHistoryIndex() public view returns (uint256) {
return supply.tokenActionIndex;
}
///////////////////
// Events
///////////////////
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event MintingPaused(address indexed initiator);
event MintingResumed(address indexed initiator);
event Reopened(address indexed initiator);
event MetaDataChanged(address indexed initiator, string name, string symbol, address baseCurrency, uint256 cap, uint256 goal);
event RolesChanged(address indexed initiator, address pauseControl, address tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
event TokenActionIndexIncreased(uint256 tokenActionIndex, uint256 blocknumber);
///////////////////
// Modifiers
///////////////////
modifier onlyPauseControl() {
require(msg.sender == roles.pauseControl, "pauseCtrl");
_;
}
//can be overwritten in inherited contracts...
function _canDoAnytime() internal view returns (bool) {
return false;
}
modifier onlyOwnerOrOverruled() {
if(_canDoAnytime() == false) {
require(isOwner(), "only owner");
}
_;
}
modifier canMint() {
if(_canDoAnytime() == false) {
require(canMintLogic(), "canMint");
}
_;
}
function canMintLogic() private view returns (bool) {
return msg.sender == roles.mintControl && availability.tokenAlive && !availability.mintingPhaseFinished && !availability.mintingPaused;
}
//can be overwritten in inherited contracts...
function checkCanSetMetadata() internal returns (bool) {
if(_canDoAnytime() == false) {
require(isOwner(), "owner only");
require(!availability.tokenAlive, "alive");
require(!availability.mintingPhaseFinished, "finished");
}
return true;
}
modifier canSetMetadata() {
checkCanSetMetadata();
_;
}
modifier onlyTokenAlive() {
require(availability.tokenAlive, "not alive");
_;
}
modifier onlyTokenRescueControl() {
require(msg.sender == roles.tokenRescueControl, "rescueCtrl");
_;
}
modifier canTransfer() {
require(availability.transfersEnabled, "paused");
_;
}
///////////////////
// Set / Get Metadata
///////////////////
/// @notice Change the token's metadata.
/// @dev Time is via block.timestamp (check crowdsale contract)
/// @param _nameParam The name of the token.
/// @param _symbolParam The symbol of the token.
/// @param _tokenBaseCurrency The base currency.
/// @param _cap The max amount of tokens that can be minted.
/// @param _goal The goal of tokens that should be sold.
/// @param _startTime Time when crowdsale should start.
/// @param _endTime Time when crowdsale should end.
function setMetaData(
string calldata _nameParam,
string calldata _symbolParam,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external
canSetMetadata
{
require(_cap >= _goal, "cap higher goal");
_name = _nameParam;
_symbol = _symbolParam;
baseCurrency = _tokenBaseCurrency;
supply.cap = _cap;
supply.goal = _goal;
supply.startTime = _startTime;
supply.endTime = _endTime;
emit MetaDataChanged(msg.sender, _nameParam, _symbolParam, _tokenBaseCurrency, _cap, _goal);
}
/// @notice Set mint control role. Usually this is CONDA's controller.
/// @param _mintControl Contract address or wallet that should be allowed to mint.
function setMintControl(address _mintControl) public canSetMetadata { //ERROR: what on UPGRADE
roles.setMintControl(_mintControl);
}
/// @notice Set roles.
/// @param _pauseControl address that is allowed to pause.
/// @param _tokenRescueControl address that is allowed rescue tokens.
function setRoles(address _pauseControl, address _tokenRescueControl) public
canSetMetadata
{
roles.setRoles(_pauseControl, _tokenRescueControl);
}
function setTokenAlive() public
onlyOwnerOrOverruled
{
availability.setTokenAlive();
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public canTransfer returns (bool success) {
supply.doTransfer(availability, msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition (requires allowance/approval)
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
return transferFromInternal(_from, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition (requires allowance/approval)
/// @dev modifiers in this internal method because also used by features.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFromInternal(address _from, address _to, uint256 _amount) internal canTransfer returns (bool success) {
return supply.transferFrom(availability, _from, _to, _amount);
}
/// @notice balance of `_owner` for this token
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` now (at the current index)
function balanceOf(address _owner) public view returns (uint256 balance) {
return supply.balanceOfNow(_owner);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` of his tokens
/// @dev This is a modified version of the ERC20 approve function to be a bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
return supply.approve(_spender, _amount);
}
/// @notice This method can check how much is approved by `_owner` for `_spender`
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return supply.allowed[_owner][_spender];
}
/// @notice This function makes it easy to get the total number of tokens
/// @return The total number of tokens now (at current index)
function totalSupply() public view returns (uint256) {
return supply.totalSupplyNow();
}
/// @notice Increase the amount of tokens that an owner allowed to a spender.
/// @dev approve should be called when allowed[_spender] == 0. To increment
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
return supply.increaseApproval(_spender, _addedValue);
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// approve should be called when allowed[_spender] == 0. To decrement
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
return supply.decreaseApproval(_spender, _subtractedValue);
}
////////////////
// Miniting
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _to The beneficiary who receives increased balance.
/// @param _amount The amount of balance increase.
function mint(address _to, uint256 _amount) public canMint returns (bool) {
return supply.mint(_to, _amount);
}
/// @notice Function to stop minting new tokens
/// @return True if the operation was successful.
function finishMinting() public onlyOwnerOrOverruled returns (bool) {
return availability.finishMinting();
}
////////////////
// Rescue Tokens
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _foreignTokenAddress The address from which the balance will be retrieved
/// @param _to beneficiary
function rescueToken(address _foreignTokenAddress, address _to)
public
onlyTokenRescueControl
{
availability.rescueToken(_foreignTokenAddress, _to);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @notice Someone's token balance of this token
/// @dev Queries the balance of `_owner` at `_specificTransfersAndMintsIndex`
/// @param _owner The address from which the balance will be retrieved
/// @param _specificTransfersAndMintsIndex The balance at index
/// @return The balance at `_specificTransfersAndMintsIndex`
function balanceOfAt(address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256) {
return supply.balanceOfAt(_owner, _specificTransfersAndMintsIndex);
}
/// @notice Total amount of tokens at `_specificTransfersAndMintsIndex`.
/// @param _specificTransfersAndMintsIndex The totalSupply at index
/// @return The total amount of tokens at `_specificTransfersAndMintsIndex`
function totalSupplyAt(uint256 _specificTransfersAndMintsIndex) public view returns(uint256) {
return supply.totalSupplyAt(_specificTransfersAndMintsIndex);
}
////////////////
// Enable tokens transfers
////////////////
/// @dev this function is not public and can be overwritten
function enableTransferInternal(bool _transfersEnabled) internal {
availability.pauseTransfer(_transfersEnabled);
}
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed
function enableTransfers(bool _transfersEnabled) public
onlyOwnerOrOverruled
{
enableTransferInternal(_transfersEnabled);
}
////////////////
// Pausing token for unforeseen reasons
////////////////
/// @dev `pauseTransfer` is an alias for `enableTransfers` using the pauseControl modifier
/// @param _transfersEnabled False if transfers are allowed
function pauseTransfer(bool _transfersEnabled) public
onlyPauseControl
{
enableTransferInternal(_transfersEnabled);
}
/// @dev `pauseCapitalIncreaseOrDecrease` can pause mint
/// @param _mintingEnabled False if minting is allowed
function pauseCapitalIncreaseOrDecrease(bool _mintingEnabled) public
onlyPauseControl
{
availability.pauseCapitalIncreaseOrDecrease(_mintingEnabled);
}
/// @dev capitalControl (if exists) can reopen the crowdsale.
/// this function is not public and can be overwritten
function reopenCrowdsaleInternal() internal returns (bool) {
return availability.reopenCrowdsale();
}
/// @dev capitalControl (if exists) can enforce a transferFrom e.g. in case of lost wallet.
/// this function is not public and can be overwritten
function enforcedTransferFromInternal(address _from, address _to, uint256 _value, bool _fullAmountRequired) internal returns (bool) {
return supply.enforcedTransferFrom(availability, _from, _to, _value, _fullAmountRequired);
}
}
// File: contracts/assettoken/interfaces/ICRWDController.sol
interface ICRWDController {
function transferParticipantsVerification(address _underlyingCurrency, address _from, address _to, uint256 _amount) external returns (bool); //from AssetToken
}
// File: contracts/assettoken/interfaces/IGlobalIndex.sol
interface IGlobalIndex {
function getControllerAddress() external view returns (address);
function setControllerAddress(address _newControllerAddress) external;
}
// File: contracts/assettoken/abstract/ICRWDAssetToken.sol
contract ICRWDAssetToken is IBasicAssetTokenFull {
function setGlobalIndexAddress(address _globalIndexAddress) public;
}
// File: contracts/assettoken/CRWDAssetToken.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title CRWD AssetToken. This contract inherits basic functionality and extends calls to controller. */
contract CRWDAssetToken is BasicAssetToken, ICRWDAssetToken {
using SafeMath for uint256;
IGlobalIndex public globalIndex;
function getControllerAddress() public view returns (address) {
return globalIndex.getControllerAddress();
}
/** @dev ERC20 transfer function overlay to transfer tokens and call controller.
* @param _to The recipient address.
* @param _amount The amount.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
ICRWDController(getControllerAddress()).transferParticipantsVerification(baseCurrency, msg.sender, _to, _amount);
return super.transfer(_to, _amount);
}
/** @dev ERC20 transferFrom function overlay to transfer tokens and call controller.
* @param _from The sender address (requires approval).
* @param _to The recipient address.
* @param _amount The amount.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
ICRWDController(getControllerAddress()).transferParticipantsVerification(baseCurrency, _from, _to, _amount);
return super.transferFrom(_from, _to, _amount);
}
/** @dev Mint function overlay to mint/create tokens.
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public canMint returns (bool) {
return super.mint(_to,_amount);
}
/** @dev Set address of GlobalIndex.
* @param _globalIndexAddress Address to be used for current destination e.g. controller lookup.
*/
function setGlobalIndexAddress(address _globalIndexAddress) public onlyOwner {
globalIndex = IGlobalIndex(_globalIndexAddress);
}
}
// File: contracts/assettoken/feature/FeatureCapitalControl.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title FeatureCapitalControl. */
contract FeatureCapitalControl is ICRWDAssetToken {
////////////////
// Variables
////////////////
//if set can mint after finished. E.g. a notary.
address public capitalControl;
////////////////
// Constructor
////////////////
constructor(address _capitalControl) public {
capitalControl = _capitalControl;
enableTransferInternal(false); //disable transfer as default
}
////////////////
// Modifiers
////////////////
//override: skip certain modifier checks as capitalControl
function _canDoAnytime() internal view returns (bool) {
return msg.sender == capitalControl;
}
modifier onlyCapitalControl() {
require(msg.sender == capitalControl, "permission");
_;
}
////////////////
// Functions
////////////////
/// @notice set capitalControl
/// @dev this looks unprotected but has a checkCanSetMetadata check.
/// depending on inheritance this can be done
/// before alive and any time by capitalControl
function setCapitalControl(address _capitalControl) public {
require(checkCanSetMetadata(), "forbidden");
capitalControl = _capitalControl;
}
/// @notice as capital control I can pass my ownership to a new address (e.g. private key leaked).
/// @param _capitalControl new capitalControl address
function updateCapitalControl(address _capitalControl) public onlyCapitalControl {
capitalControl = _capitalControl;
}
////////////////
// Reopen crowdsale (by capitalControl e.g. notary)
////////////////
/// @notice capitalControl can reopen the crowdsale.
function reopenCrowdsale() public onlyCapitalControl returns (bool) {
return reopenCrowdsaleInternal();
}
}
// File: contracts/assettoken/feature/FeatureCapitalControlWithForcedTransferFrom.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title FeatureCapitalControlWithForcedTransferFrom. */
contract FeatureCapitalControlWithForcedTransferFrom is FeatureCapitalControl {
///////////////////
// Constructor
///////////////////
constructor(address _capitalControl) FeatureCapitalControl(_capitalControl) public { }
///////////////////
// Events
///////////////////
event SelfApprovedTransfer(address indexed initiator, address indexed from, address indexed to, uint256 value);
///////////////////
// Overrides
///////////////////
//override: transferFrom that has special self-approve behaviour when executed as capitalControl
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
if (msg.sender == capitalControl) {
return enforcedTransferFromInternal(_from, _to, _value, true);
} else {
return transferFromInternal(_from, _to, _value);
}
}
}
// File: contracts/assettoken/STOs/AssetTokenT001.sol
/** @title AssetTokenT001 Token. A CRWDAssetToken with CapitalControl and LostWallet feature */
contract AssetTokenT001 is CRWDAssetToken, FeatureCapitalControlWithForcedTransferFrom
{
constructor(address _capitalControl) FeatureCapitalControlWithForcedTransferFrom(_capitalControl) public {}
} | File: contracts/assettoken/interfaces/IGlobalIndex.sol | interface IGlobalIndex {
function getControllerAddress() external view returns (address);
function setControllerAddress(address _newControllerAddress) external;
}
| 6,461,926 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
// -------------
// FANCY BEE DAO
//
// This DAO esponsible for managing the treasury and all other contracts including:
// - BeeNFT, HiveNFT, OutfitNFT and FancyBsGov (ERC20)
//
// All operations that involve a royalty toe the DAO must be mediated
// thought this contract.
//
// The DAO is goverened though the FancyBsGovenor contract and the FancyBsGov voting token.
// -------------
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Royalty.sol";
contract FancyBsDAO is Ownable {
struct hive{
uint8 percent;
uint256 balance;
}
mapping (address=> hive) public hiveMap;
mapping (uint16=> address) public reverseHiveMap;
uint16 hiveCount = 0;
uint256 public treasury; //Amount to be distributed
uint256 public retained; //Amount held for DAO
uint256 public daoPercent;
BeeNFT public beeNFT;
HiveNFT public hiveNFT;//temp
OutfitNFT public outfitNFT;
FancyBsGov public votingToken;
FancyBsGovenor public governor;
constructor(){
beeNFT = new BeeNFT();
hiveNFT = new HiveNFT();
votingToken = new FancyBsGov();
governor = new FancyBsGovenor(votingToken);
}
// Allows the DAO to take ownership of the whole ecosystem.
function LockOwnership() public onlyOwner {
beeNFT.transferOwnership(address(this));
hiveNFT.transferOwnership(address(this));
votingToken.transferOwnership(address(this));
}
//Recieve all ETH there. ERC20s are permissioned and accumulated in the ERC20 contract
receive() external payable {
treasury += msg.value;
}
//
// Interface to Beekeeper
//
//TODO
//
function dressMe(uint256 _beeID, uint256 _outfitID) public payable {
require ( msg.value != 1^11, "Please send exactly x 100 GWei.");
outfitNFT.attachToBee(_outfitID, address(beeNFT), _beeID);
beeNFT.attachOutfit(_beeID, address(outfitNFT), _outfitID);
treasury += msg.value;
}
//
// Interface to outfitNFT//
//
// TODO
//
//
// Governance functions - these are functions that the Governance contract is able to call
//
function distributeFunds(uint256 _amount) public onlyOwner{
uint256 amt;
if (_amount == 0 || _amount > treasury){
amt = treasury;
}
//send the amounts.
//TODO PROTECT RE-ENTRANCY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
amt -= amt*10000/daoPercent;
uint256 t = amt/hiveCount;
for (uint16 i=0; i<hiveCount; i++){
treasury -= t;
(bool sent, bytes memory d) = reverseHiveMap[i].call{value: t}("");
require(sent, "Failed to send Ether");
}
retained += treasury;
treasury = 0;
}
function addCharity(address _addr) public onlyOwner{
hiveMap[_addr].balance = 0;
hiveMap[_addr].percent = 5; //default
hiveCount++;
}
function setCharityPercent(address _addr, uint8 _p ) public onlyOwner{
hiveMap[_addr].percent = _p;
}
function setDAOPercent(uint8 _p) public onlyOwner{
daoPercent = _p;
}
}
// -------------
// FANCY BEE NFT
// -------------
contract BeeNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, Ownable, ERC721Burnable {
address internal fancyDAO = msg.sender;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
mapping (uint256=>address) outfitNFT;
mapping (uint256=>uint256) outfitTokenID;
constructor() ERC721("FancyBee", "FBEE") {}
//TODO - register for ERC-1820
function royaltyInfo(uint256 _tokenId, uint256 _price) external view returns (address receiver, uint256 amount){
require (_tokenId>0, "TokenID out of range");
return (fancyDAO, _price/10);
}
//==================================
// SPECIAL FUNCIONALITY
//
function _tokenExists(uint256 _id) public view returns (bool){
return (true); /// TODO we need to find the structure/map used by the framework.
}
// Called by the DAO to attach an outfit to a bee.
function attachOutfit(uint256 _beeID, address _contract, uint256 _outfitID) public {
require(msg.sender == fancyDAO, "Not fancyDAO");
require (!_tokenExists(_beeID), "Invalid bee"); //check bee exists.
require (!OutfitNFT(_contract)._tokenExists(_outfitID), "Invalid outfit"); //check the outfit exists
require (OutfitNFT(_contract).isOwnedBy(_beeID), "Bee is not owner"); //check the outfit it ours
_setTokenURI(_beeID, OutfitNFT(_contract).tokenURI(_outfitID)); //can we reference it?
outfitNFT[_beeID] = _contract;
outfitTokenID[_beeID] = _outfitID;
}
// Added from Marco's repo
/*
function mintToken(address owner, string memory metadataURI)
public
returns (uint256)
{
require( balanceOf(msg.sender) == 0, "Sorry, only one bee per person." );
require( totalSupply() < totalBeeSupply, "Sorry only 5 are available at this time. ");
_tokenIds.increment();
uint256 id = _tokenIds.current();
_safeMint(owner, id);
_setTokenURI(id, metadataURI);
return id;
}*/
//==================================
//
// Template behaviour...
//
function _baseURI() internal pure override returns (string memory) {
return "IPFS://...";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function safeMint(address to) public onlyOwner {
_safeMint(to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// --------------
// FANCY HIVE NFT
// --------------
contract HiveNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, Ownable, ERC721Burnable {
address internal fancyDAO = msg.sender;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
constructor() ERC721("FancyHive", "FBHV") {}
//
//ALLOW ROYALTIES
//TODO - register for ERC-1820
//
function royaltyInfo(uint256 _tokenId, uint256 _price) external view returns (address receiver, uint256 amount){
require (_tokenId>0, "TokenID out of range");
return (fancyDAO, _price/10);
}
//
// SPECIAL FUNCIONALITY
//
function _tokenExists(uint256 _id) internal view returns (bool){
return (true);
}
// Added from Marco's repo
/* function mintToken(address owner, string memory metadataURI)
public
returns (uint256)
{
require( balanceOf(msg.sender) == 0, "Sorry, only one bee per person." );
require( totalSupply() < totalBeeSupply, "Sorry only 5 are available at this time. ");
_tokenIds.increment();
uint256 id = _tokenIds.current();
_safeMint(owner, id);
_setTokenURI(id, metadataURI);
return id;
}*/
//==================================
//
// Template behaviour...
//
function _baseURI() internal pure override returns (string memory) {
return "IPFS://...";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function safeMint(address to) public onlyOwner {
_safeMint(to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// --------------
// FANCY OUTFIT NFT
// --------------
contract OutfitNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, Ownable, ERC721Burnable {
address internal fancyDAO = msg.sender;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
mapping (uint256=>address) beeNFT;
mapping (uint256=>uint256) beeTokenID;
constructor() ERC721("FancyOutfit", "FBOF") {}
//TODO - register for ERC-1820
//TODO Should split it 50:50 with th creator. Register Outfit with as royalty receiver and split.
function royaltyInfo(uint256 _tokenId, uint256 _price) external view returns (address receiver, uint256 amount){
require (_tokenId>0, "TokenID out of range");
return (fancyDAO, _price/10); //TODO need to forward price/5 to the creator.
}
//==================================
// SPECIAL FUNCIONALITY
//
function _tokenExists(uint256 _id) public view returns (bool){
return (true);
}
function isOwnedBy(uint256 _beeID) public view returns (bool){
return(beeTokenID[_beeID] !=0);
}
// Called by the DAO to ask outfit to attach to a bee. Must be called _before_ calling the bee
function attachToBee(uint256 _outfitID, address _contract, uint256 _beeID) public {
require(msg.sender == fancyDAO, "Not fancyDAO");
require (!_tokenExists(_outfitID), "Invalid outfit"); //check outfit exists.
require (!BeeNFT(_contract)._tokenExists(_beeID), "Invalid bee"); //check the bee exists
require (beeNFT[_outfitID] == address(0) || beeTokenID[_outfitID] == 0, "Already taken"); //check the outfit it available
beeNFT[_outfitID] = _contract;
beeTokenID[_outfitID] = _beeID;
// TODO _setTokenOWner(_contract, _beeID); //only the bee can control now (need better system)
}
// Added from Marco's repo
/*
function mintToken(address owner, string memory metadataURI)
public
returns (uint256)
{
require( balanceOf(msg.sender) == 0, "Sorry, only one bee per person." );
require( totalSupply() < totalBeeSupply, "Sorry only 5 are available at this time. ");
_tokenIds.increment();
uint256 id = _tokenIds.current();
_safeMint(owner, id);
_setTokenURI(id, metadataURI);
return id;
}*/
//==================================
function _baseURI() internal pure override returns (string memory) {
return "IPFS://...";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function safeMint(address to) public onlyOwner {
_safeMint(to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// --------------------------
// FANCY BEE GOVERNANCE TOKEN
// --------------------------
contract FancyBsGov is ERC20, ERC20Burnable, ERC20Snapshot, Ownable, ERC20Permit, ERC20Votes {
constructor() ERC20("FancyBsGov", "FBG") ERC20Permit("FancyBGov") {}
address internal fancyDAO = msg.sender;
function snapshot() public onlyOwner {
_snapshot();
}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 amount)
internal
override(ERC20, ERC20Snapshot)
{
super._beforeTokenTransfer(from, to, amount);
}
function _afterTokenTransfer(address from, address to, uint256 amount)
internal
override(ERC20, ERC20Votes)
{
super._afterTokenTransfer(from, to, amount);
}
function _mint(address to, uint256 amount)
internal
override(ERC20, ERC20Votes)
{
super._mint(to, amount);
}
function _burn(address account, uint256 amount)
internal
override(ERC20, ERC20Votes)
{
super._burn(account, amount);
}
}
// -------------------------
// FANCY BEE VOTING GOVERNOR
// -------------------------
import "@openzeppelin/contracts/governance/Governor.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol";
contract FancyBsGovenor is Governor, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction {
address internal fancyDAO = msg.sender;
constructor(ERC20Votes _token)
Governor("FancyBsGovenor")
GovernorVotes(_token)
GovernorVotesQuorumFraction(4)
{}
function votingDelay() public pure override returns (uint256) {
return 1; // 1 block
}
function votingPeriod() public pure override returns (uint256) {
return 45818; // 1 week
}
// The following functions are overrides required by Solidity.
function quorum(uint256 blockNumber)
public
view
override(IGovernor, GovernorVotesQuorumFraction)
returns (uint256)
{
return super.quorum(blockNumber);
}
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernor, GovernorVotes)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
}
| Added from Marco's repo | function mintToken(address owner, string memory metadataURI)
public
returns (uint256)
{
require( balanceOf(msg.sender) == 0, "Sorry, only one bee per person." );
require( totalSupply() < totalBeeSupply, "Sorry only 5 are available at this time. ");
_tokenIds.increment();
uint256 id = _tokenIds.current();
_safeMint(owner, id);
_setTokenURI(id, metadataURI);
return id;
}*/
| 12,826,130 |
pragma solidity ^0.4.13;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract IERC20Token {
function totalSupply() public constant returns (uint256 totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
// NOT IERC20 Token
function hasSDC(address _address,uint256 _quantity) public returns (bool success);
function hasSDCC(address _address,uint256 _quantity) public returns (bool success);
function eliminateSDCC(address _address,uint256 _quantity) public returns (bool success);
function createSDCC(address _address,uint256 _quantity) public returns (bool success);
function createSDC(address _address,uint256 _init_quantity, uint256 _quantity) public returns (bool success);
function stakeSDC(address _address, uint256 amount) public returns(bool);
function endStake(address _address, uint256 amount) public returns(bool);
function chipBalanceOf(address _address) public returns (uint256 _amount);
function transferChips(address _from, address _to, uint256 _value) public returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract Lockable is Owned{
uint256 public lockedUntilBlock;
event ContractLocked(uint256 _untilBlock, string _reason);
modifier lockAffected {
require(block.number > lockedUntilBlock);
_;
}
function lockFromSelf(uint256 _untilBlock, string _reason) internal {
lockedUntilBlock = _untilBlock;
ContractLocked(_untilBlock, _reason);
}
function lockUntil(uint256 _untilBlock, string _reason) onlyOwner {
lockedUntilBlock = _untilBlock;
ContractLocked(_untilBlock, _reason);
}
}
contract Token is IERC20Token, Lockable {
using SafeMath for uint256;
/* Public variables of the token */
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public supply;
address public crowdsaleContractAddress;
/* Private variables of the token */
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
/* Events */
event Mint(address indexed _to, uint256 _value);
function Token(){
}
/* Returns total supply of issued tokens */
function totalSupply() constant returns (uint256) {
return supply;
}
/* Returns balance of address */
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/* Transfers tokens from your address to other */
function transfer(address _to, uint256 _value) lockAffected returns (bool success) {
require(_to != 0x0 && _to != address(this));
balances[msg.sender] = balances[msg.sender].sub(_value); // Deduct senders balance
balances[_to] = balances[_to].add(_value); // Add recivers blaance
Transfer(msg.sender, _to, _value); // Raise Transfer event
return true;
}
/* Approve other address to spend tokens on your account */
function approve(address _spender, uint256 _value) lockAffected returns (bool success) {
allowances[msg.sender][_spender] = _value; // Set allowance
Approval(msg.sender, _spender, _value); // Raise Approval event
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(_to != 0x0 && _to != address(this));
balances[_from] = balances[_from].sub(_value); // Deduct senders balance
balances[_to] = balances[_to].add(_value); // Add recipient blaance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); // Deduct allowance for this address
Transfer(_from, _to, _value); // Raise Transfer event
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
function mintTokens(address _to, uint256 _amount) {
require(msg.sender == crowdsaleContractAddress);
supply = supply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner {
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
}
//----------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract SoundcoinsToken is Token {
address _teamAddress; // Account 3
address _saleAddress;
uint256 availableSupply = 250000000;
uint256 minableSupply = 750000000;
address public SoundcoinsAddress;
/* Balances for ships */
uint256 public total_SDCC_supply = 0;
mapping (address => uint256) balances_chips;
mapping (address => uint256) holdings_SDC;
uint256 holdingsSupply = 0;
modifier onlyAuthorized {
require(msg.sender == SoundcoinsAddress);
_;
}
/* Initializes contract */
function SoundcoinsToken(address _crowdsaleContract) public {
standard = "Soundcoins Token V1.0";
name = "Soundcoins";
symbol = "SDC";
decimals = 0;
supply = 1000000000;
_teamAddress = msg.sender;
balances[msg.sender] = 100000000;
_saleAddress = _crowdsaleContract;
balances[_crowdsaleContract] = 150000000;
}
/********* */
/* TOOLS */
/********* */
function getAvailableSupply() public returns (uint256){
return availableSupply;
}
function getMinableSupply() public returns (uint256){
return minableSupply;
}
function getHoldingsSupply() public returns (uint256){
return holdingsSupply;
}
function getSDCCSupply() public returns (uint256){
return total_SDCC_supply;
}
function getSoundcoinsAddress() public returns (address){
return SoundcoinsAddress;
}
// See if Address has Enough SDC
function hasSDC(address _address,uint256 _quantity) public returns (bool success){
return (balances[_address] >= _quantity);
}
// See if Address has Enough SDC
function hasSDCC(address _address, uint256 _quantity) public returns (bool success){
return (chipBalanceOf(_address) >= _quantity);
}
/*SDC*/
function createSDC(address _address, uint256 _init_quantity, uint256 _quantity) onlyAuthorized public returns (bool success){
require(minableSupply >= 0);
balances[_address] = balances[_address].add(_quantity);
availableSupply = availableSupply.add(_quantity);
holdings_SDC[_address] = holdings_SDC[_address].sub(_init_quantity);
minableSupply = minableSupply.sub(_quantity.sub(_init_quantity));
holdingsSupply = holdingsSupply.sub(_init_quantity);
return true;
}
function eliminateSDCC(address _address, uint256 _quantity) onlyAuthorized public returns (bool success){
balances_chips[_address] = balances_chips[_address].sub(_quantity);
total_SDCC_supply = total_SDCC_supply.sub(_quantity);
return true;
}
function createSDCC(address _address, uint256 _quantity) onlyAuthorized public returns (bool success){
balances_chips[_address] = balances_chips[_address].add(_quantity);
total_SDCC_supply = total_SDCC_supply.add(_quantity);
return true;
}
function chipBalanceOf(address _address) public returns (uint256 _amount) {
return balances_chips[_address];
}
function transferChips(address _from, address _to, uint256 _value) onlyAuthorized public returns (bool success) {
require(_to != 0x0 && _to != address(msg.sender));
balances_chips[_from] = balances_chips[_from].sub(_value); // Deduct senders balance
balances_chips[_to] = balances_chips[_to].add(_value); // Add recivers blaance
return true;
}
function changeSoundcoinsContract(address _newAddress) public onlyOwner {
SoundcoinsAddress = _newAddress;
}
function stakeSDC(address _address, uint256 amount) onlyAuthorized public returns(bool){
balances[_address] = balances[_address].sub(amount);
availableSupply = availableSupply.sub(amount);
holdings_SDC[_address] = holdings_SDC[_address].add(amount);
holdingsSupply = holdingsSupply.add(amount);
return true;
}
function endStake(address _address, uint256 amount) onlyAuthorized public returns(bool){
balances[_address] = balances[_address].add(amount);
availableSupply = availableSupply.add(amount);
holdings_SDC[_address] = holdings_SDC[_address].sub(amount);
holdingsSupply = holdingsSupply.sub(amount);
return true;
}
} | Returns total supply of issued tokens / | function totalSupply() constant returns (uint256) {
return supply;
}
| 12,730,365 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface IERC677Receiver {
function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface ISideToken {
function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
interface ISideTokenFactory {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address);
event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
// https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
// solium-disable-next-line security/no-inline-assembly
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./zeppelin/token/ERC777/ERC777.sol";
import "./IERC677Receiver.sol";
import "./ISideToken.sol";
import "./LibEIP712.sol";
contract SideToken is ISideToken, ERC777 {
using Address for address;
using SafeMath for uint256;
address public minter;
uint256 private _granularity;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
// ERC677 Transfer Event
event Transfer(address,address,uint256,bytes);
constructor(string memory _tokenName, string memory _tokenSymbol, address _minterAddr, uint256 _newGranularity)
ERC777(_tokenName, _tokenSymbol, new address[](0)) {
require(_minterAddr != address(0), "SideToken: Empty Minter");
require(_newGranularity >= 1, "SideToken: Granularity < 1");
minter = _minterAddr;
_granularity = _newGranularity;
uint chainId;
// solium-disable-next-line security/no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(
name(),
"1",
chainId,
address(this)
);
}
modifier onlyMinter() {
require(_msgSender() == minter, "SideToken: Caller is not the minter");
_;
}
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external onlyMinter override
{
_mint(_msgSender(), account, amount, userData, operatorData);
}
/**
* @dev ERC677 transfer token with additional data if the recipient is a contact.
* @param recipient The address to transfer to.
* @param amount The amount to be transferred.
* @param data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address recipient, uint amount, bytes calldata data)
external returns (bool success)
{
address from = _msgSender();
_send(from, from, recipient, amount, data, "", false);
emit Transfer(from, recipient, amount, data);
IERC677Receiver(recipient).onTokenTransfer(from, amount, data);
return true;
}
function granularity() public view override returns (uint256) {
return _granularity;
}
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "SideToken: EXPIRED");
bytes32 digest = LibEIP712.hashEIP712Message(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "SideToken: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./zeppelin/ownership/Secondary.sol";
import "./ISideTokenFactory.sol";
import "./SideToken.sol";
contract SideTokenFactory is ISideTokenFactory, Secondary {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity)
external onlyPrimary override returns(address) {
address sideToken = address(new SideToken(name, symbol, primary(), granularity));
emit SideTokenCreated(sideToken, symbol, granularity);
return sideToken;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/*
* @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 returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `_account`.
* - `_interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `_implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address _account, bytes32 _interfaceHash, address _implementer) external;
/**
* @dev Returns the implementer of `_interfaceHash` for `_account`. If no such
* implementer is registered, returns the zero address.
*
* If `_interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `_account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address _account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../GSN/Context.sol";
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
abstract contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () {
_primary = _msgSender();
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../GSN/Context.sol";
import "./IERC777.sol";
import "./IERC777Recipient.sol";
import "./IERC777Sender.sol";
import "../../token/ERC20/IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../introspection/IERC1820Registry.sol";
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory aName,
string memory aSymbol,
address[] memory theDefaultOperators
) {
_name = aName;
_symbol = aSymbol;
_defaultOperatorsArray = theDefaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override(IERC777) returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override(IERC777) returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure override returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override(IERC777) returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external override(IERC777) {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes calldata data) external override(IERC777) {
_burn(_msgSender(), _msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override(IERC777) returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external override(IERC777) {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external override(IERC777) {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override(IERC777) returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external override(IERC777)
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator");
_send(_msgSender(), sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData)
external override(IERC777) {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator");
_burn(_msgSender(), account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender)
public view override(IERC20) returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external override(IERC20) returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount)
external override(IERC20) returns (bool) {
require(recipient != address(0), "ERC777: transfer to zero address");
require(holder != address(0), "ERC777: transfer from zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
require(account != address(0), "ERC777: mint to zero address");
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from zero address");
require(to != address(0), "ERC777: send to zero address");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal
{
require(from != address(0), "ERC777: burn from zero address");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
function _approve(address holder, address spender, uint256 value) internal {
// TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is
// currently unnecessary.
//require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See `IERC1820Registry` and
* `ERC1820Implementer`.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See `IERC777Sender` and `IERC777Recipient`.
*
* Emits a `Sent` event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the `tokensReceived`
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See `IERC777Sender`.
*
* Emits a `Burned` event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See `operatorSend` and `operatorBurn`.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See `isOperatorFor`.
*
* Emits an `AuthorizedOperator` event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Make an account an operator of the caller.
*
* See `isOperatorFor` and `defaultOperators`.
*
* Emits a `RevokedOperator` event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if `authorizeOperator` was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* `revokeOperator`, in which case `isOperatorFor` will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See `IERC777Sender` and `IERC777Recipient`.
*
* Emits a `Sent` event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the `tokensReceived`
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See `IERC777Sender`.
*
* Emits a `Burned` event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
function decimals() external returns (uint8);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of `IERC777` tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* See `IERC1820Registry` and `ERC1820Implementer`.
*/
interface IERC777Recipient {
/**
* @dev Called by an `IERC777` token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* `IERC777.balanceOf`, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* `IERC777` Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* See `IERC1820Registry` and `ERC1820Implementer`.
*/
interface IERC777Sender {
/**
* @dev Called by an `IERC777` token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* `IERC777.balanceOf`, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma abicoder v2;
/**
* @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 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: 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);
}
}
}
}
| See {IERC20-allowance}. Note that operator and allowance concepts are orthogonal: operators may not have allowance, and accounts with allowance may not be operators themselves./ | function allowance(address holder, address spender)
public view override(IERC20) returns (uint256) {
return _allowances[holder][spender];
}
| 1,423,175 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./UniswapV2/UniswapV2Router02.sol";
import '../vendors/interfaces/IPactSwapRouter.sol';
import '../vendors/interfaces/IPactSwapFactory.sol';
import '../vendors/interfaces/IWETH.sol';
import '../vendors/libraries/UniswapV2Library.sol';
import '../vendors/libraries/TransferHelper.sol';
contract PactSwapRouter is IPactSwapRouter, UniswapV2Router02 {
constructor(address _factory, address _WETH) UniswapV2Router02(_factory, _WETH) public {}
modifier onlyGovernance() {
require(IPactSwapFactory(factory).governance() == msg.sender, "Governance: caller is not the governance");
_;
}
function removeIncentivesPoolLiquidity(
address tokenA,
address tokenB,
uint amountTokenAMin,
uint amountTokenBMin,
uint deadline
) public virtual override ensure(deadline) onlyGovernance() returns (uint amountTokenA, uint amountTokenB) {
IPactSwapFactory factory_ = IPactSwapFactory(factory);
require(factory_.incentivesPool() != address(0), "removeIncentivesPoolLiquidity: incentivesPool is zero address");
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
(amountTokenA, amountTokenB) = removeLiquidity(
tokenA,
tokenB,
IERC20(pair).balanceOf(factory_.incentivesPool()),
amountTokenAMin,
amountTokenBMin,
address(this),
deadline
);
withdrawTo(tokenA, factory_.incentivesPool(), amountTokenA);
withdrawTo(tokenB, factory_.incentivesPool(), amountTokenB);
}
function withdrawTo(address token, address account, uint amountToken) internal {
if (token == WETH) {
IWETH(WETH).withdraw(amountToken);
TransferHelper.safeTransferETH(account, amountToken);
} else {
TransferHelper.safeTransfer(token, account, amountToken);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '../../vendors/interfaces/IUniswapV2Factory.sol';
import "../../vendors/interfaces/IUniswapV2Router01.sol";
import '../../vendors/interfaces/IERC20.sol';
import '../../vendors/interfaces/IWETH.sol';
import "../../vendors/interfaces/IUniswapV2Router02.sol";
import '../../vendors/libraries/UniswapV2Library.sol';
import '../../vendors/libraries/TransferHelper.sol';
import "../../vendors/libraries/SafeMath.sol";
contract UniswapV2Router02 is IUniswapV2Router02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
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,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.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,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.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,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.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,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint 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,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : 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,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : 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,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint 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,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : 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(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.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(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.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 (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint 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(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint 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(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint 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(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// 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;
interface IGovernanceOwnable {
event GovernanceSetTransferred(address indexed previousGovernance, address indexed newGovernance);
function governance() external view returns (address);
function setGovernance(address newGovernance) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IUniswapV2Factory.sol";
import "./IGovernanceOwnable.sol";
import "./IWithIncentivesPool.sol";
interface IPactSwapFactory is IUniswapV2Factory, IWithIncentivesPool, IGovernanceOwnable {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IPactSwapRouter {
function removeIncentivesPoolLiquidity(
address tokenA,
address tokenB,
uint amountTokenAMin,
uint amountTokenBMin,
uint deadline
) external returns (uint amountToken, uint amountPact);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC20.sol";
interface IUniswapV2ERC20 is IERC20 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IUniswapV2ERC20.sol";
interface IUniswapV2Pair is IUniswapV2ERC20 {
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IUniswapV2Router01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IWithIncentivesPool {
event IncentivesPoolSetTransferred(address indexed previousIncentivesPool, address indexed newIncentivesPool);
function incentivesPool() external view returns (address);
function setIncentivesPool(address newIncentivesPool) external;
}
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// 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');
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '../interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'a7fea0ca09af3ad115eed91f6f5abeff5b69eb113dceedb234968ab0b2fe1216' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
| SPDX-License-Identifier: MIT | interface IUniswapV2Router01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
| 1,345,200 |
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
import "./InscribeInterface.sol";
import "./InscribeMetaDataInterface.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract InscribeMetadata is InscribeMetaDataInterface {
struct BaseURI {
string baseUri;
address owner;
}
// Mapping from baseUriId to a BaseURI struct
mapping (uint256 => BaseURI) internal _baseUriMapping;
/**
* @dev The latest baseUriId. This ID increases by 1 every time a new
* base URI is created.
*/
uint256 internal latestBaseUriId;
/**
* @dev See {InscribeMetaDataInterface-addBaseURI}.
*/
function addBaseURI(string memory baseUri) public override {
emit BaseURIAdded(latestBaseUriId, baseUri);
_baseUriMapping[latestBaseUriId] = BaseURI(baseUri, msg.sender);
latestBaseUriId++;
}
/**
* @dev See {InscribeMetaDataInterface-migrateBaseURI}.
*/
function migrateBaseURI(uint256 baseUriId, string memory baseUri) external override {
BaseURI memory uri = _baseUriMapping[baseUriId];
require(_baseURIExists(uri), "Base URI does not exist");
require(uri.owner == msg.sender, "Only owner of the URI may migrate the URI");
emit BaseURIModified(baseUriId, baseUri);
_baseUriMapping[baseUriId] = BaseURI(baseUri, msg.sender);
}
/**
* @dev See {InscribeMetaDataInterface-getBaseURI}.
*/
function getBaseURI(uint256 baseUriId) public view override returns (string memory baseURI) {
BaseURI memory uri = _baseUriMapping[baseUriId];
require(_baseURIExists(uri), "Base URI does not exist");
return uri.baseUri;
}
/**
* @dev Verifies if the base URI at the specified Id exists
*/
function _baseURIExists(BaseURI memory uri) internal pure returns (bool) {
return uri.owner != address(0);
}
}
contract Inscribe is InscribeInterface, InscribeMetadata {
using Strings for uint256;
using ECDSA for bytes32;
// --- Storage of inscriptions ---
// In order to save storage, we emit the contentHash instead of storing it on chain
// Thus frontends must verify that the content hash that was emitted must match
// Mapping from inscription ID to the address of the inscriber
mapping (uint256 => address) private _inscribers;
// Mapping from inscription Id to a hash of the nftAddress and tokenId
mapping (uint256 => bytes32) private _locationHashes;
// Mapping from inscription ID to base URI IDs
// Inscriptions managed by an operator use base uri
// URIs are of the form {baseUrl}{inscriptionId}
mapping (uint256 => uint256) private _baseURIIds;
// Mapping from inscription ID to inscriptionURI
mapping (uint256 => string) private _inscriptionURIs;
// mapping from an inscriber address to a mapping of location hash to nonces
mapping (address => mapping (bytes32 => uint256)) private _nonces;
// --- Approvals ---
// Mapping from an NFT address to a mapping of a token ID to an approved address
mapping (address => mapping (uint256 => address)) private _inscriptionApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes32 public immutable domainSeparator;
// Used for calculationg inscription Ids when adding without a sig
uint256 latestInscriptionId;
//keccak256("AddInscription(address nftAddress,uint256 tokenId,bytes32 contentHash,uint256 nonce)");
bytes32 public constant ADD_INSCRIPTION_TYPEHASH = 0x6b7aae47ef1cd82bf33fbe47ef7d5d948c32a966662d56eb728bd4a5ed1082ea;
constructor () {
latestBaseUriId = 1;
latestInscriptionId = 1;
uint256 chainID;
assembly {
chainID := chainid()
}
domainSeparator = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("Inscribe")),
keccak256(bytes("1")),
chainID,
address(this)
)
);
}
/**
* @dev See {InscribeInterface-getInscriber}.
*/
function getInscriber(uint256 inscriptionId) external view override returns (address) {
address inscriber = _inscribers[inscriptionId];
require(inscriber != address(0), "Inscription does not exist");
return inscriber;
}
/**
* @dev See {InscribeInterface-verifyInscription}.
*/
function verifyInscription(uint256 inscriptionId, address nftAddress, uint256 tokenId) public view override returns (bool) {
bytes32 locationHash = _locationHashes[inscriptionId];
return locationHash == keccak256(abi.encodePacked(nftAddress, tokenId));
}
/**
* @dev See {InscribeInterface-getInscriptionURI}.
*/
function getNonce(address inscriber, address nftAddress, uint256 tokenId) external view override returns (uint256) {
bytes32 locationHash = keccak256(abi.encodePacked(nftAddress, tokenId));
return _nonces[inscriber][locationHash];
}
/**
* @dev See {InscribeInterface-getInscriptionURI}.
*/
function getInscriptionURI(uint256 inscriptionId) external view override returns (string memory inscriptionURI) {
require(_inscriptionExists(inscriptionId), "Inscription does not exist");
uint256 baseUriId = _baseURIIds[inscriptionId];
if (baseUriId == 0) {
return _inscriptionURIs[inscriptionId];
} else {
BaseURI memory uri = _baseUriMapping[baseUriId];
require(_baseURIExists(uri), "Base URI does not exist");
return string(abi.encodePacked(uri.baseUri, inscriptionId.toString()));
}
}
/**
* @dev See {InscribeApprovalInterface-approve}.
*/
function approve(address to, address nftAddress, uint256 tokenId) public override {
address owner = _ownerOf(nftAddress, tokenId);
require(owner != address(0), "Nonexistent token ID");
require(to != owner, "Cannot approve the 'to' address as it belongs to the nft owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "Approve caller is not owner nor approved for all");
_approve(to, nftAddress, tokenId);
}
/**
* @dev See {InscribeApprovalInterface-getApproved}.
*/
function getApproved(address nftAddress, uint256 tokenId) public view override returns (address) {
return _inscriptionApprovals[nftAddress][tokenId];
}
/**
* @dev See {InscribeApprovalInterface-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) external override {
require(operator != msg.sender, "Operator cannot be the same as the caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {InscribeApprovalInterface-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {InscribeApprovalInterface-addInscriptionWithNoSig}.
*/
function addInscriptionWithNoSig(
address nftAddress,
uint256 tokenId,
bytes32 contentHash,
uint256 baseUriId
) external override {
require(nftAddress != address(0));
require(baseUriId != 0);
require(_isApprovedOrOwner(msg.sender, nftAddress, tokenId));
BaseURI memory uri = _baseUriMapping[baseUriId];
require(_baseURIExists(uri), "Base URI does not exist");
_baseURIIds[latestInscriptionId] = baseUriId;
bytes32 locationHash = keccak256(abi.encodePacked(nftAddress, tokenId));
_addInscription(nftAddress, tokenId, msg.sender, contentHash, latestInscriptionId, locationHash);
latestInscriptionId++;
}
/**
* @dev See {InscribeInterface-addInscription}.
*/
function addInscriptionWithBaseUriId(
address nftAddress,
uint256 tokenId,
address inscriber,
bytes32 contentHash,
uint256 baseUriId,
uint256 nonce,
bytes calldata sig
) external override {
require(inscriber != address(0));
require(nftAddress != address(0));
bytes32 locationHash = keccak256(abi.encodePacked(nftAddress, tokenId));
require(_nonces[inscriber][locationHash] == nonce, "Nonce mismatch, sign again with the nonce from `getNonce`");
bytes32 digest = _generateAddInscriptionHash(nftAddress, tokenId, contentHash, nonce);
// Verifies the signature
require(_recoverSigner(digest, sig) == inscriber, "Recovered address does not match inscriber");
require(_isApprovedOrOwner(msg.sender, nftAddress, tokenId), "NFT does not belong to msg sender");
uint256 inscriptionId = latestInscriptionId;
// Add metadata
BaseURI memory uri = _baseUriMapping[baseUriId];
require(_baseURIExists(uri), "Base URI does not exist");
_baseURIIds[inscriptionId] = baseUriId;
// Update nonce
_nonces[inscriber][locationHash]++;
// Store inscription
_addInscription(nftAddress, tokenId, inscriber, contentHash, inscriptionId, locationHash);
latestInscriptionId++;
}
/**
* @dev See {InscribeInterface-addInscription}.
*/
function addInscriptionWithInscriptionUri(
address nftAddress,
uint256 tokenId,
address inscriber,
bytes32 contentHash,
string calldata inscriptionURI,
uint256 nonce,
bytes calldata sig
) external override {
require(inscriber != address(0));
require(nftAddress != address(0));
bytes32 locationHash = keccak256(abi.encodePacked(nftAddress, tokenId));
require(_nonces[inscriber][locationHash] == nonce, "Nonce mismatch, sign again with the nonce from `getNonce`");
bytes32 digest = _generateAddInscriptionHash(nftAddress, tokenId, contentHash, nonce);
// Verifies the signature
require(_recoverSigner(digest, sig) == inscriber, "Recovered address does not match inscriber");
require(_isApprovedOrOwner(msg.sender, nftAddress, tokenId), "NFT does not belong to msg sender");
// Add metadata
uint256 inscriptionId = latestInscriptionId;
_baseURIIds[inscriptionId] = 0;
_inscriptionURIs[inscriptionId] = inscriptionURI;
// Update nonce
_nonces[inscriber][locationHash]++;
_addInscription(nftAddress, tokenId, inscriber, contentHash, inscriptionId, locationHash);
latestInscriptionId++;
}
/**
* @dev See {InscribeInterface-removeInscription}.
*/
function removeInscription(uint256 inscriptionId, address nftAddress, uint256 tokenId) external override {
require(_inscriptionExists(inscriptionId), "Inscription does not exist at this ID");
require(verifyInscription(inscriptionId, nftAddress, tokenId), "Verifies nftAddress and tokenId are legitimate");
// Verifies that the msg.sender has permissions to remove an inscription
require(_isApprovedOrOwner(msg.sender, nftAddress, tokenId), "Caller does not own inscription or is not approved");
_removeInscription(inscriptionId, nftAddress, tokenId);
}
// -- Migrating URIs
// Migrations are necessary if you would like an inscription operator to host your content hash
//
function migrateURI(
uint256 inscriptionId,
uint256 baseUriId,
address nftAddress,
uint256 tokenId
) external override {
require(_inscriptionExists(inscriptionId), "Inscription does not exist at this ID");
require(verifyInscription(inscriptionId, nftAddress, tokenId), "Verifies nftAddress and tokenId are legitimate");
require(_isApprovedOrOwner(msg.sender, nftAddress, tokenId), "Caller does not own inscription or is not approved");
_baseURIIds[inscriptionId] = baseUriId;
delete _inscriptionURIs[inscriptionId];
}
function migrateURI(
uint256 inscriptionId,
string calldata inscriptionURI,
address nftAddress,
uint256 tokenId
) external override{
require(_inscriptionExists(inscriptionId), "Inscription does not exist at this ID");
require(verifyInscription(inscriptionId, nftAddress, tokenId), "Verifies nftAddress and tokenId are legitimate");
require(_isApprovedOrOwner(msg.sender, nftAddress, tokenId), "Caller does not own inscription or is not approved");
_baseURIIds[inscriptionId] = 0;
_inscriptionURIs[inscriptionId] = inscriptionURI;
}
/**
* @dev Returns whether the `inscriber` is allowed to add or remove an inscription to `tokenId` at `nftAddress`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address inscriber, address nftAddress, uint256 tokenId) private view returns (bool) {
address owner = _ownerOf(nftAddress, tokenId);
require(owner != address(0), "Nonexistent token ID");
return (inscriber == owner || getApproved(nftAddress, tokenId) == inscriber || isApprovedForAll(owner, inscriber));
}
/**
* @dev Adds an approval on chain
*/
function _approve(address to, address nftAddress, uint256 tokenId) internal {
_inscriptionApprovals[nftAddress][tokenId] = to;
emit Approval(_ownerOf(nftAddress, tokenId), to, nftAddress, tokenId);
}
/**
* @dev Returns the owner of `tokenId` at `nftAddress`
*/
function _ownerOf(address nftAddress, uint256 tokenId) internal view returns (address){
IERC721 nftContractInterface = IERC721(nftAddress);
return nftContractInterface.ownerOf(tokenId);
}
/**
* @dev Removes an inscription on-chain after all requirements were met
*/
function _removeInscription(uint256 inscriptionId, address nftAddress, uint256 tokenId) private {
// Clear approvals from the previous inscriber
_approve(address(0), nftAddress, tokenId);
// Remove Inscription
address inscriber = _inscribers[inscriptionId];
delete _inscribers[inscriptionId];
delete _locationHashes[inscriptionId];
delete _inscriptionURIs[inscriptionId];
emit InscriptionRemoved(
inscriptionId,
nftAddress,
tokenId,
inscriber);
}
/**
* @dev Adds an inscription on-chain with optional URI after all requirements were met
*/
function _addInscription(
address nftAddress,
uint256 tokenId,
address inscriber,
bytes32 contentHash,
uint256 inscriptionId,
bytes32 locationHash
) private {
_inscribers[inscriptionId] = inscriber;
_locationHashes[inscriptionId] = locationHash;
emit InscriptionAdded(
inscriptionId,
nftAddress,
tokenId,
inscriber,
contentHash
);
}
/**
* @dev Verifies if an inscription at `inscriptionID` exists
*/
function _inscriptionExists(uint256 inscriptionId) private view returns (bool) {
return _inscribers[inscriptionId] != address(0);
}
/**
* @dev Generates the EIP712 hash that was signed
*/
function _generateAddInscriptionHash(
address nftAddress,
uint256 tokenId,
bytes32 contentHash,
uint256 nonce
) private view returns (bytes32) {
// Recreate signed message
return keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(
abi.encode(
ADD_INSCRIPTION_TYPEHASH,
nftAddress,
tokenId,
contentHash,
nonce
)
)
)
);
}
function _recoverSigner(bytes32 _hash, bytes memory _sig) private pure returns (address) {
address signer = ECDSA.recover(_hash, _sig);
require(signer != address(0));
return signer;
}
}
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
interface InscribeInterface {
/**
* @dev Emitted when an 'owner' gives an 'inscriber' one time approval to add or remove an inscription for
* the 'tokenId' at 'nftAddress'.
*/
event Approval(address indexed owner, address indexed inscriber, address indexed nftAddress, uint256 tokenId);
// Emitted when an 'owner' gives or removes an 'operator' approval to add or remove inscriptions to all of their NFTs.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
// Emitted when an inscription is added to an NFT at 'nftAddress' with 'tokenId'
event InscriptionAdded(uint256 indexed inscriptionId,
address indexed nftAddress,
uint256 tokenId,
address indexed inscriber,
bytes32 contentHash);
// Emitted when an inscription is removed from an NFT at 'nftAddress' with 'tokenId'
event InscriptionRemoved(uint256 indexed inscriptionId,
address indexed nftAddress,
uint256 tokenId,
address indexed inscriber);
/**
* @dev Fetches the inscriber for the inscription at `inscriptionId`
*/
function getInscriber(uint256 inscriptionId) external view returns (address);
/**
* @dev Verifies that `inscriptionId` is inscribed to the NFT at `nftAddress`, `tokenId`
*/
function verifyInscription(uint256 inscriptionId, address nftAddress, uint256 tokenId) external view returns (bool);
/**
* @dev Fetches the nonce used while signing a signature.
* Note: If a user signs multiple times on the same NFT, only one sig will go through.
*/
function getNonce(address inscriber, address nftAddress, uint256 tokenId) external view returns (uint256);
/**
* @dev Fetches the inscriptionURI at inscriptionId
*
* Requirements:
*
* - `inscriptionId` inscriptionId must exist
*
*/
function getInscriptionURI(uint256 inscriptionId) external view returns (string memory inscriptionURI);
/**
* @dev Gives `inscriber` a one time approval to add or remove an inscription for `tokenId` at `nftAddress`
*/
function approve(address to, address nftAddress, uint256 tokenId) external;
/*
* @dev Returns the `address` approved for the `tokenId` at `nftAddress`
*/
function getApproved(address nftAddress, uint256 tokenId) external view returns (address);
/**
* @dev Similar to the ERC721 implementation, Approve or remove `operator` as an operator for the caller.
* Operators can modify any inscription for any NFT 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 inscribe or remove inscriptions for all NFTs owned by `owner`
*
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Adds an inscription on-chain to the specified NFT. This is mainly used to sign your own NFTs or for
* other smart contracts to add inscription functionality.
* @param nftAddress The NFT contract address
* @param tokenId The tokenId of the NFT that is being signed
* @param contentHash A hash of the content. This hash will not change and will be used to verify the contents in the frontend.
* This hash must be hosted by inscription operators at the baseURI in order to be considered a valid inscription.
* @param baseUriId The id of the inscription operator
*
* Requirements:
*
* - `tokenId` The user calling this method must own the `tokenId` at `nftAddress` or has been approved
*
*/
function addInscriptionWithNoSig(
address nftAddress,
uint256 tokenId,
bytes32 contentHash,
uint256 baseUriId
) external;
/**
* @dev Adds an inscription on-chain to the specified NFT. Call this method if you are using an inscription operator.
* @param nftAddress The NFT contract address
* @param tokenId The tokenId of the NFT that is being signed
* @param inscriber The address of the inscriber
* @param contentHash A hash of the content. This hash will not change and will be used to verify the contents in the frontend.
* This hash must be hosted by inscription operators at the baseURI in order to be considered a valid inscription.
* @param baseUriId The id of the inscription operator
* @param nonce A unique value to ensure every sig is different. Get this value by calling the function `getNonce`
* @param sig Signature of the hash, signed by the inscriber
*
* Requirements:
*
* - `tokenId` The user calling this method must own the `tokenId` at `nftAddress` or has been approved
*
*/
function addInscriptionWithBaseUriId(
address nftAddress,
uint256 tokenId,
address inscriber,
bytes32 contentHash,
uint256 baseUriId,
uint256 nonce,
bytes calldata sig
) external;
/**
* @dev Adds an inscription on-chain to the specified nft. Call this method if you have a specified inscription URI.
* @param nftAddress The nft contract address
* @param tokenId The tokenId of the NFT that is being signed
* @param inscriber The address of the inscriber
* @param contentHash A hash of the content. This hash will not change and will be used to verify the contents in the frontent
* @param inscriptionURI URI of where the hash is stored
* @param nonce A unique value to ensure every sig is different
* @param sig Signature of the hash, signed by the inscriber
*
* Requirements:
*
* - `tokenId` The user calling this method must own the `tokenId` at `nftAddress` or has been approved
*
*/
function addInscriptionWithInscriptionUri(
address nftAddress,
uint256 tokenId,
address inscriber,
bytes32 contentHash,
string calldata inscriptionURI,
uint256 nonce,
bytes calldata sig
) external;
/**
* @dev Removes inscription on-chain.
*
* Requirements:
*
* - `inscriptionId` The user calling this method must own the `tokenId` at `nftAddress` of the inscription at `inscriptionId` or has been approved
*/
function removeInscription(uint256 inscriptionId, address nftAddress, uint256 tokenId) external;
// -- Migrating URIs
/**
* @dev Migrations are necessary if you would like an inscription operator to host your content hash
* or if you would like to swap to a new inscription operator.
*/
function migrateURI(uint256 inscriptionId, uint256 baseUriId, address nftAddress, uint256 tokenId) external;
/**
* @dev Migrates the URI to inscription URI. This is mainly to migrate to an ipfs link. The content hash must
be stored at inscriptionURI in order to be considered valid by frontend.
*/
function migrateURI(uint256 inscriptionId, string calldata inscriptionURI, address nftAddress, uint256 tokenId) external;
}
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
interface InscribeMetaDataInterface {
/**
* @dev Emitted when a URI has been added.
*/
event BaseURIAdded(uint256 indexed baseUriId, string indexed baseUri);
/**
* @dev Emitted when a URI has been modified.
*/
event BaseURIModified(uint256 indexed baseURIId, string indexed baseURI);
/**
* @dev Adds a base URI to the contract state.
* This URI can be referenced by the URIId which is emitted from the event.
* Emits a {BaseURIAdded} event.
*/
function addBaseURI(string memory baseURI) external;
/**
* @dev Migrates a base URI. Useful if the base endpoint needs to be adjusted.
*
* Requirements:
*
* - `baseUriId` must exist.
* - Only the creator of this URI may call this function
*
* Emits a {BaseURIModified} event.
*/
function migrateBaseURI(uint256 baseUriId, string memory baseURI) external;
/**
* @dev Fetches the Base URI at `baseUriId`
*
* Requirements:
*
* - `baseUriId` baseUri must exist at `baseUriId`
*
*/
function getBaseURI(uint256 baseUriId) external view returns (string memory baseURI);
}
// 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;
/**
* @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.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 {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @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) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* 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;
/**
* @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);
}
| Verifies if the base URI at the specified Id exists/ | function _baseURIExists(BaseURI memory uri) internal pure returns (bool) {
return uri.owner != address(0);
}
| 4,800,492 |
// SPDX-License-Identifier: MIT
/*
..:---========--::..
.-=======================-:.
:===============================-:
.=======================-=============-.
:===========-:. :======: .:-==========-.
.=++=======:. :======: .:-========-.
-++++====-. :======: .-======--:
=+++++===. :======: -====----
=++++++=: :======: .-==-----
=++++++=. :======: -=------
-++++++=. :======: -------:
+++++++: :======: .-------
:++++++= :======: -------:
=++++++: :======: :-------
+++++++. :======: .-------
+++++++. :========: .-------
=++++++: :============: .-------
:++++++= :================: -------:
+++++++: :====================: .-------
-++++++=. :========================: -------:
=++++++=. :=========:-======-:=========: -=------
=++++++=: :=========: :======: :=========: .-==-----
=+++++===========: :======: :=============----
-++++=========: :======: :===========--:
.=++========. :======: .-=========-.
:===========-:. :======: .::-=========-.
:=======================-=============-.
:===============================-:
.-=======================-:.
Peace Distortion was a collaboration between Peace DAO Movement
https://juicebox.money/#/p/peace and https://peace.move.xyz/
and Artist 0xon-chain world, Discord on-chain world#4444
Thank you https://twitter.com/onchainworld for contributing the code.
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract Distortion is ERC721, Ownable {
// Keeping track of supply and displaying it.
using Counters for Counters.Counter;
Counters.Counter private distortionSupply;
constructor() ERC721("Peace DAO Movement", "PEACE") { }
/**
* @notice This shows the randomness of block 14600852 which included the mint of the 1000th original Distortion piece.
*
*/
string public constant HASH_OF_BLOCK =
"0x6e56139840a2bc1bfbba5aad5e51d8d68acf6a010a1e67f713a1d8fa371a836f";
/**
* @notice Returns the total supply of tokens airdropped.
*
*/
function totalSupply() public view returns (uint256 supply) {
return distortionSupply.current();
}
/**
* @notice Once this shows true, it cannot be reversed, making the airdrop function uncallable.
*
*/
bool public airdropPermanentlyDisabled;
/**
* @notice This function will be called to disable airdrops permanently once all the tokens have been airdropped.
*
*/
function disableAirdrop() public onlyOwner {
require(
!airdropPermanentlyDisabled,
"Once the airdrop function is disabled it cannot be re-enabled."
);
airdropPermanentlyDisabled = true;
}
/**
* @notice The airdrop function which will be permanently disabled once all tokens have been airdropped.
*
*/
function airdrop(address[] memory _to, uint256[][] memory _tokenIds)
public
onlyOwner
{
require(
!airdropPermanentlyDisabled,
"Once the airdrop is disabled, the function can never be called again."
);
for (uint256 i = 0; i < _to.length; i++) {
for (uint256 z = 0; z < _tokenIds[i].length; z++) {
_safeMint(_to[i], _tokenIds[i][z]);
distortionSupply.increment();
}
}
}
/*
░██████╗░███████╗███╗░░██╗███████╗██████╗░░█████╗░████████╗██╗██╗░░░██╗███████╗
██╔════╝░██╔════╝████╗░██║██╔════╝██╔══██╗██╔══██╗╚══██╔══╝██║██║░░░██║██╔════╝
██║░░██╗░█████╗░░██╔██╗██║█████╗░░██████╔╝███████║░░░██║░░░██║╚██╗░██╔╝█████╗░░
██║░░╚██╗██╔══╝░░██║╚████║██╔══╝░░██╔══██╗██╔══██║░░░██║░░░██║░╚████╔╝░██╔══╝░░
╚██████╔╝███████╗██║░╚███║███████╗██║░░██║██║░░██║░░░██║░░░██║░░╚██╔╝░░███████╗
░╚═════╝░╚══════╝╚═╝░░╚══╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░░╚═╝░░░╚══════╝
Everything to do with the on-chain generation of the Distortion pieces.
*/
string[] private colorNames = [
"White",
"Rose"
/*
"Red",
"Green",
"Blue",
"Gold",
"Purple"
*/
];
string[] private left = [
"rgb(140,140,140)",
"rgb(255, 26, 26)",
"rgb(92, 214, 92)",
"rgb(26, 140, 255)",
"rgb(255, 215, 0)",
"rgb(255, 128, 128)",
"rgb(192, 50, 227)"
];
string[] private right = [
"rgb(52,52,52)",
"rgb(230, 0, 0)",
"rgb(51, 204, 51)",
"rgb(0, 115, 230)",
"rgb(204, 173, 0)",
"rgb(255, 102, 102)",
"rgb(167, 40, 199)"
];
string[] private middleLeft = [
"rgb(57,57,57)",
"rgb(179, 0, 0)",
"rgb(41, 163, 41)",
"rgb(0, 89, 179)",
"rgb(153, 130, 0)",
"rgb(255, 77, 77)",
"rgb(127, 32, 150)"
];
string[] private middleRight = [
"rgb(20,20,20)",
"rgb(128, 0, 0)",
"rgb(31, 122, 31)",
"rgb(0, 64, 128)",
"rgb(179, 152, 0)",
"rgb(255, 51, 51)",
"rgb(98, 19, 117)"
];
string[] private frequencies = ["", "0", "00"];
function generateString(
string memory name,
uint256 tokenId,
string[] memory array
) internal pure returns (string memory) {
uint256 rand = uint256(
keccak256(abi.encodePacked(name, toString(tokenId)))
) % array.length;
string memory output = string(
abi.encodePacked(array[rand % array.length])
);
return output;
}
function generateColorNumber(string memory name, uint256 tokenId)
internal
pure
returns (uint256)
{
uint256 output;
uint256 rand = uint256(
keccak256(abi.encodePacked(name, toString(tokenId)))
) % 100;
if (keccak256(bytes(HASH_OF_BLOCK)) == keccak256(bytes(""))) {
output = 0; //unrevealed
} else {
if (rand <= 15) {
output = 1; //Red with 15% rarity.
} else if (rand > 15 && rand <= 30) {
output = 2; //Green with 15% rarity.
} else if (rand > 30 && rand <= 45) {
output = 3; //Blue with 15% rarity.
} else if (rand > 45 && rand <= 75) {
output = 0; //Black with 30% rarity.
} else if (rand > 75 && rand <= 80) {
output = 4; //Gold with 5% rarity.
} else if (rand > 80 && rand <= 90) {
output = 5; //Rose with 10% rarity.
} else if (rand > 90) {
output = 6; //Purple with 10% rarity.
}
}
return output;
}
function generateNum(
string memory name,
uint256 tokenId,
string memory genVar,
uint256 low,
uint256 high
) internal pure returns (string memory) {
uint256 difference = high - low;
uint256 randomnumber = (uint256(
keccak256(abi.encodePacked(genVar, tokenId, name))
) % difference) + 1;
randomnumber = randomnumber + low;
return toString(randomnumber);
}
function generateNumUint(
string memory name,
uint256 tokenId,
string memory genVar,
uint256 low,
uint256 high
) internal pure returns (uint256) {
uint256 difference = high - low;
uint256 randomnumber = (uint256(
keccak256(abi.encodePacked(genVar, tokenId, name))
) % difference) + 1;
randomnumber = randomnumber + low;
return randomnumber;
}
function genDefs(uint256 tokenId) internal view returns (string memory) {
string memory output;
string memory xFrequency = generateString("xF", tokenId, frequencies);
string memory yFrequency = generateString("yF", tokenId, frequencies);
string memory scale = generateNum(
"scale",
tokenId,
HASH_OF_BLOCK,
10,
40
);
if (keccak256(bytes(HASH_OF_BLOCK)) == keccak256(bytes(""))) {
xFrequency = "";
yFrequency = "";
scale = "30";
}
output = string(
abi.encodePacked(
'<defs><filter id="squares" x="-30%" y="-30%" width="160%" height="160%"> <feTurbulence type="turbulence" baseFrequency="',
"0.",
xFrequency,
"5 0.",
yFrequency,
"5",
'" numOctaves="10" seed="" result="turbulence"> <animate attributeName="seed" dur="0.3s" repeatCount="indefinite" calcMode="discrete" values="1;2;3;4;5;6;7;8;9;1"/> </feTurbulence> <feDisplacementMap in="SourceGraphic" in2="turbulence" scale="',
scale,
'" xChannelSelector="R" yChannelSelector="G" /> </filter> </defs>'
)
);
return output;
}
function genMiddle(uint256 tokenId) internal pure returns (string memory) {
string memory translate = toString(
divide(
generateNumUint("scale", tokenId, HASH_OF_BLOCK, 10, 40),
5,
0
)
);
string[5] memory p;
if (keccak256(bytes(HASH_OF_BLOCK)) == keccak256(bytes(""))) {
translate = "6";
}
p[
0
] = '<style alt="surround"> #1 { stroke-dasharray: 50,50,150 } .cls-2 { fill: rgba(140,140,140, 1);}.cls-3 {fill: rgba(140,140,140, 0.3);}</style><g style="filter: url(#squares);" opacity="100%" id="1"> <g transform="translate(-';
p[1] = translate;
p[2] = ", -";
p[3] = translate;
p[4] = ')" >';
string memory output = string(
abi.encodePacked(p[0], p[1], p[2], p[3], p[4])
);
return output;
}
function genSquares(uint256 tokenId) internal view returns (string memory) {
string memory output1;
string memory output2;
uint256 ringCount = generateNumUint(
"ringCount",
tokenId,
HASH_OF_BLOCK,
5,
15
);
string[2] memory xywh;
uint256 ringScaling = divide(25, ringCount, 0);
if (keccak256(bytes(HASH_OF_BLOCK)) == keccak256(bytes(""))) {
ringCount = 5;
ringScaling = 5;
}
for (uint256 i = 0; i < ringCount; i++) {
xywh[0] = toString(ringScaling * i + 5);
xywh[1] = toString(100 - (ringScaling * i + 5) * 2);
output1 = string(
abi.encodePacked(
'<g style="animation: glitch 1.',
toString(i),
's infinite;"> <rect x="',
xywh[0],
'%" y="',
xywh[0],
'%" width="',
xywh[1],
'%" height="',
xywh[1],
'%" fill="none" stroke="',
left[generateColorNumber("color", tokenId)],
'" id="1" /> </g>'
)
);
output2 = string(abi.encodePacked(output1, output2));
}
return output2;
}
function genEnd(uint256 tokenId) internal view returns (string memory) {
uint256 colorNum = generateColorNumber("color", tokenId);
string[13] memory p;
p[
0
] = '</g> </g><g style="animation: glitch 0.5s infinite;filter: url(#squares);"> <g transform="scale(0.40) translate(750, 750)" style="opacity:40%"> <path fill="';
p[1] = right[colorNum];
p[
2
] = '" d="M500,0C223.86,0,0,223.86,0,500s223.86,500,500,500,500-223.86,500-500S776.14,0,500,0ZM878,500a376.44,376.44,0,0,1-82.55,235.81L560,500.34V126.71C740.27,155.46,878,311.64,878,500ZM440,873.29a375.83,375.83,0,0,1-147.13-57L440,669.15ZM560,670,706.59,816.63A375.73,375.73,0,0,1,560,873.29ZM440,126.71V499.45L204.13,735.32A376.48,376.48,0,0,1,122,500C122,311.64,259.73,155.46,440,126.71Z"/>';
p[3] = "</g> </g> </svg>";
string memory output = string(abi.encodePacked(p[0], p[1], p[2], p[3]));
return output;
}
/**
* @notice Generate the SVG of any Distortion piece, including token IDs that are out of bounds.
*
*/
function generateDistortion(uint256 tokenId)
public
view
returns (string memory)
{
string memory output;
output = string(
abi.encodePacked(
'<svg width="750px" height="750px" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background-color: ',
colorNames[generateColorNumber("color", tokenId)],
';"><style> @keyframes glitch { 0% {transform: translate(0px); opacity: 0.15;} 7% {transform: translate(2px); opacity: 0.65;} 45% {transform: translate(0px); opacity: 0.35;} 50% {transform: translate(-2px); opacity: 0.85;} 100% {transform: translate(0px); opacity: 0.25;} } </style> <defs> <filter id="background" x="-20%" y="-20%" width="140%" height="140%" filterUnits="objectBoundingBox" primitiveUnits="userSpaceOnUse" color-interpolation-filters="linearRGB"> <feTurbulence type="fractalNoise" baseFrequency="10" numOctaves="4" seed="1" stitchTiles="stitch" x="0%" y="0%" width="100%" height="100%" result="turbulence"> <animate attributeName="seed" dur="1s" repeatCount="indefinite" calcMode="discrete" values="1;2;3;4;5;6;7;8;9;10" /> </feTurbulence> <feSpecularLighting surfaceScale="10" specularExponent="10" lighting-color="#fff" width="100%" height="100%"> <animate attributeName="surfaceScale" dur="1s" repeatCount="indefinite" calcMode="discrete" values="10;11;12;13;14;15;14;13;12;11" /> <feDistantLight elevation="100"/> </feSpecularLighting> </filter> </defs> <g opacity="10%"> <rect width="700" height="700" fill="hsl(23, 0%, 100%)" filter="url(#background)"></rect></g>',
genDefs(tokenId),
genMiddle(tokenId),
genSquares(tokenId),
genEnd(tokenId)
)
);
return output;
}
function getFrequency(uint256 tokenId) internal view returns (uint256) {
uint256[2] memory xy;
string memory y = generateString("yF", tokenId, frequencies);
string memory x = generateString("xF", tokenId, frequencies);
if (keccak256(bytes(x)) == keccak256(bytes("0"))) {
xy[0] = 2;
} else if (keccak256(bytes(x)) == keccak256(bytes("00"))) {
xy[0] = 1;
} else {
xy[0] = 3;
}
if (keccak256(bytes(y)) == keccak256(bytes("0"))) {
xy[1] = 2;
} else if (keccak256(bytes(y)) == keccak256(bytes("00"))) {
xy[1] = 1;
} else {
xy[1] = 3;
}
return xy[0] * xy[1];
}
/**
* @notice
*
*/
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"Token doesn't exist. Try using the generateDistortion function to generate non-existant pieces."
);
string memory ringCount = generateNum(
"ringCount",
tokenId,
HASH_OF_BLOCK,
5,
15
);
string memory scale = generateNum(
"scale",
tokenId,
HASH_OF_BLOCK,
10,
40
);
uint256 freq = getFrequency(tokenId);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Distortion #',
toString(tokenId),
'","attributes": [ { "trait_type": "Color", "value": "',
colorNames[generateColorNumber("color", tokenId)],
'" }, { "trait_type": "Distortion Scale", "value": ',
scale,
' }, { "trait_type": "Rings", "value": ',
ringCount,
' }, { "trait_type": "Frequency Multiple", "value": ',
toString(freq),
" }]",
', "description": "Distortion is a fully hand-typed 100% on-chain art collection.", "image": "data:image/svg+xml;base64,',
Base64.encode(
bytes(
string(
abi.encodePacked(
generateDistortion(tokenId)
)
)
)
),
'"}'
)
)
)
);
string memory output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
}
/**
* @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);
}
function divide(
uint256 a,
uint256 b,
uint256 precision
) internal pure returns (uint256) {
return (a * (10**precision)) / b;
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)
)
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
} | The airdrop function which will be permanently disabled once all tokens have been airdropped./ | function airdrop(address[] memory _to, uint256[][] memory _tokenIds)
public
onlyOwner
{
require(
!airdropPermanentlyDisabled,
"Once the airdrop is disabled, the function can never be called again."
);
for (uint256 i = 0; i < _to.length; i++) {
for (uint256 z = 0; z < _tokenIds[i].length; z++) {
_safeMint(_to[i], _tokenIds[i][z]);
distortionSupply.increment();
}
}
}
░██████╗░███████╗███╗░░██╗███████╗██████╗░░█████╗░████████╗██╗██╗░░░██╗███████╗
██╔════╝░██╔════╝████╗░██║██╔════╝██╔══██╗██╔══██╗╚══██╔══╝██║██║░░░██║██╔════╝
██║░░██╗░█████╗░░██╔██╗██║█████╗░░██████╔╝███████║░░░██║░░░██║╚██╗░██╔╝█████╗░░
██║░░╚██╗██╔══╝░░██║╚████║██╔══╝░░██╔══██╗██╔══██║░░░██║░░░██║░╚████╔╝░██╔══╝░░
╚██████╔╝███████╗██║░╚███║███████╗██║░░██║██║░░██║░░░██║░░░██║░░╚██╔╝░░███████╗
░╚═════╝░╚══════╝╚═╝░░╚══╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░░╚═╝░░░╚══════╝
Everything to do with the on-chain generation of the Distortion pieces.
string[] private colorNames = [
"White",
"Rose"
"Green",
"Blue",
"Gold",
"Purple"
string[] private left = [
"rgb(140,140,140)",
"rgb(255, 26, 26)",
"rgb(92, 214, 92)",
"rgb(26, 140, 255)",
"rgb(255, 215, 0)",
"rgb(255, 128, 128)",
"rgb(192, 50, 227)"
];
string[] private right = [
"rgb(52,52,52)",
"rgb(230, 0, 0)",
"rgb(51, 204, 51)",
"rgb(0, 115, 230)",
"rgb(204, 173, 0)",
"rgb(255, 102, 102)",
"rgb(167, 40, 199)"
];
string[] private middleLeft = [
"rgb(57,57,57)",
"rgb(179, 0, 0)",
"rgb(41, 163, 41)",
"rgb(0, 89, 179)",
"rgb(153, 130, 0)",
"rgb(255, 77, 77)",
"rgb(127, 32, 150)"
];
string[] private middleRight = [
"rgb(20,20,20)",
"rgb(128, 0, 0)",
"rgb(31, 122, 31)",
"rgb(0, 64, 128)",
"rgb(179, 152, 0)",
"rgb(255, 51, 51)",
"rgb(98, 19, 117)"
];
string[] private frequencies = ["", "0", "00"];
| 11,942,754 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../interfaces/AggregatorValidatorInterface.sol";
import "../interfaces/TypeAndVersionInterface.sol";
import "../interfaces/AccessControllerInterface.sol";
import "../SimpleWriteAccessController.sol";
/* dev dependencies - to be re/moved after audit */
import "./vendor/arb-bridge-eth/v0.8.0-custom/contracts/bridge/interfaces/IInbox.sol";
import "./interfaces/FlagsInterface.sol";
/**
* @title ArbitrumValidator
* @notice Allows to raise and lower Flags on the Arbitrum network through its Layer 1 contracts
* - The internal AccessController controls the access of the validate method
* - Gas configuration is controlled by a configurable external SimpleWriteAccessController
* - Funds on the contract are managed by the owner
*/
contract ArbitrumValidator is TypeAndVersionInterface, AggregatorValidatorInterface, SimpleWriteAccessController {
// Config for L1 -> L2 `createRetryableTicket` call
struct GasConfiguration {
uint256 maxSubmissionCost;
uint256 maxGasPrice;
uint256 gasCostL2;
uint256 gasLimitL2;
address refundableAddress;
}
/// @dev Follows: https://eips.ethereum.org/EIPS/eip-1967
address constant private FLAG_ARBITRUM_SEQ_OFFLINE = address(bytes20(bytes32(uint256(keccak256("chainlink.flags.arbitrum-seq-offline")) - 1)));
bytes constant private CALL_RAISE_FLAG = abi.encodeWithSelector(FlagsInterface.raiseFlag.selector, FLAG_ARBITRUM_SEQ_OFFLINE);
bytes constant private CALL_LOWER_FLAG = abi.encodeWithSelector(FlagsInterface.lowerFlag.selector, FLAG_ARBITRUM_SEQ_OFFLINE);
address private s_l2FlagsAddress;
IInbox private s_inbox;
AccessControllerInterface private s_gasConfigAccessController;
GasConfiguration private s_gasConfig;
/**
* @notice emitted when a new gas configuration is set
* @param maxSubmissionCost maximum cost willing to pay on L2
* @param maxGasPrice maximum gas price to pay on L2
* @param gasCostL2 value to send to L2 to cover gas fee
* @param refundableAddress address where gas excess on L2 will be sent
*/
event GasConfigurationSet(
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address indexed refundableAddress
);
/**
* @notice emitted when a new gas access-control contract is set
* @param previous the address prior to the current setting
* @param current the address of the new access-control contract
*/
event GasAccessControllerSet(
address indexed previous,
address indexed current
);
/**
* @param inboxAddress address of the Arbitrum Inbox L1 contract
* @param l2FlagsAddress address of the Chainlink L2 Flags contract
* @param gasConfigAccessControllerAddress address of the access controller for managing gas price on Arbitrum
* @param maxSubmissionCost maximum cost willing to pay on L2
* @param maxGasPrice maximum gas price to pay on L2
* @param gasCostL2 value to send to L2 to cover gas fee
* @param gasLimitL2 gas limit for immediate L2 execution attempt. A value around 1M should be sufficient
* @param refundableAddress address where gas excess on L2 will be sent
*/
constructor(
address inboxAddress,
address l2FlagsAddress,
address gasConfigAccessControllerAddress,
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address refundableAddress
) {
require(inboxAddress != address(0), "Invalid Inbox contract address");
require(l2FlagsAddress != address(0), "Invalid Flags contract address");
s_inbox = IInbox(inboxAddress);
s_gasConfigAccessController = AccessControllerInterface(gasConfigAccessControllerAddress);
s_l2FlagsAddress = l2FlagsAddress;
_setGasConfiguration(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
}
/**
* @notice versions:
*
* - ArbitrumValidator 0.1.0: initial release
*
* @inheritdoc TypeAndVersionInterface
*/
function typeAndVersion()
external
pure
virtual
override
returns (
string memory
)
{
return "ArbitrumValidator 0.1.0";
}
/// @return L2 Flags contract address
function l2Flags()
external
view
virtual
returns (address)
{
return s_l2FlagsAddress;
}
/// @return Arbitrum Inbox contract address
function inbox()
external
view
virtual
returns (address)
{
return address(s_inbox);
}
/// @return gas config AccessControllerInterface contract address
function gasConfigAccessController()
external
view
virtual
returns (address)
{
return address(s_gasConfigAccessController);
}
/// @return stored GasConfiguration
function gasConfig()
external
view
virtual
returns (GasConfiguration memory)
{
return s_gasConfig;
}
/// @notice makes this contract payable as it need funds to pay for L2 transactions fees on L1.
receive() external payable {}
/**
* @notice withdraws all funds availbale in this contract to the msg.sender
* @dev only owner can call this
*/
function withdrawFunds()
external
onlyOwner()
{
address payable to = payable(msg.sender);
to.transfer(address(this).balance);
}
/**
* @notice withdraws all funds availbale in this contract to the address specified
* @dev only owner can call this
* @param to address where to send the funds
*/
function withdrawFundsTo(
address payable to
)
external
onlyOwner()
{
to.transfer(address(this).balance);
}
/**
* @notice sets gas config AccessControllerInterface contract
* @dev only owner can call this
* @param accessController new AccessControllerInterface contract address
*/
function setGasAccessController(
address accessController
)
external
onlyOwner
{
_setGasAccessController(accessController);
}
/**
* @notice sets Arbitrum gas configuration
* @dev access control provided by s_gasConfigAccessController
* @param maxSubmissionCost maximum cost willing to pay on L2
* @param maxGasPrice maximum gas price to pay on L2
* @param gasCostL2 value to send to L2 to cover gas fee
* @param gasLimitL2 gas limit for immediate L2 execution attempt. A value around 1M should be sufficient
* @param refundableAddress address where gas excess on L2 will be sent
*/
function setGasConfiguration(
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address refundableAddress
)
external
{
require(s_gasConfigAccessController.hasAccess(msg.sender, msg.data), "Access required to set config");
_setGasConfiguration(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
}
/**
* @notice validate method updates the state of an L2 Flag in case of change on the Arbitrum Sequencer.
* A one answer considers the service as offline.
* In case the previous answer is the same as the current it does not trigger any tx on L2. In other case,
* a retryable ticket is created on the Arbitrum L1 Inbox contract. The tx gas fee can be paid from this
* contract providing a value, or the same address on L2.
* @dev access control provided internally by SimpleWriteAccessController
* @param previousAnswer previous aggregator answer
* @param currentAnswer new aggregator answer
*/
function validate(
uint256 /* previousRoundId */,
int256 previousAnswer,
uint256 /* currentRoundId */,
int256 currentAnswer
)
external
override
checkAccess()
returns (bool)
{
// Avoids resending to L2 the same tx on every call
if (previousAnswer == currentAnswer) {
return true;
}
int isServiceOffline = 1;
// NOTICE: if gasCostL2 is zero the payment is processed on L2 so the L2 address needs to be funded, as it will
// paying the fee. We also ignore the returned msg number, that can be queried via the InboxMessageDelivered event.
s_inbox.createRetryableTicket{value: s_gasConfig.gasCostL2}(
s_l2FlagsAddress,
0, // L2 call value
// NOTICE: maxSubmissionCost info will possibly become available on L1 after the London fork. At that time this
// contract could start querying/calculating it directly so we wouldn't need to configure it statically. On L2 this
// info is available via `ArbRetryableTx.getSubmissionPrice`.
s_gasConfig.maxSubmissionCost, // Max submission cost of sending data length
s_gasConfig.refundableAddress, // excessFeeRefundAddress
s_gasConfig.refundableAddress, // callValueRefundAddress
s_gasConfig.gasLimitL2,
s_gasConfig.maxGasPrice,
currentAnswer == isServiceOffline ? CALL_RAISE_FLAG : CALL_LOWER_FLAG
);
return true;
}
function _setGasConfiguration(
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address refundableAddress
)
internal
{
// L2 will pay the fee if gasCostL2 is zero
if (gasCostL2 > 0) {
uint256 minGasCostValue = maxSubmissionCost + gasLimitL2 * maxGasPrice;
require(gasCostL2 >= minGasCostValue, "Gas cost provided is too low");
}
s_gasConfig = GasConfiguration(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
emit GasConfigurationSet(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
}
function _setGasAccessController(
address accessController
)
internal
{
address previousAccessController = address(s_gasConfigAccessController);
if (accessController != previousAccessController) {
s_gasConfigAccessController = AccessControllerInterface(accessController);
emit GasAccessControllerSet(previousAccessController, accessController);
}
}
}
| withdraws all funds availbale in this contract to the address specified only owner can call this to address where to send the funds/ | function withdrawFundsTo(
address payable to
)
external
onlyOwner()
{
to.transfer(address(this).balance);
}
| 6,451,171 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
// This is only kept for backward compatability / upgrading
import {OwnableUpgradeable} from "../oz/access/OwnableUpgradeable.sol";
import {EnumerableMapUpgradeable, ERC721PausableUpgradeable, IERC721Upgradeable, ERC721Upgradeable} from "../oz/token/ERC721/ERC721PausableUpgradeable.sol";
import {IRegistrar} from "../interfaces/IRegistrar.sol";
import {StorageSlot} from "../oz/utils/StorageSlot.sol";
import {BeaconProxy} from "../oz/proxy/beacon/BeaconProxy.sol";
import {IZNSHub} from "../interfaces/IZNSHub.sol";
contract Registrar is
IRegistrar,
OwnableUpgradeable,
ERC721PausableUpgradeable
{
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
// Data recorded for each domain
struct DomainRecord {
address minter;
bool metadataLocked;
address metadataLockedBy;
address controller;
uint256 royaltyAmount;
uint256 parentId;
address subdomainContract;
}
// A map of addresses that are authorised to register domains.
mapping(address => bool) public controllers;
// A mapping of domain id's to domain data
// This essentially expands the internal ERC721's token storage to additional fields
mapping(uint256 => DomainRecord) public records;
/**
* @dev Storage slot with the admin of the contract.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
// The beacon address
address public beacon;
// If this is a subdomain contract these will be set
uint256 public rootDomainId;
address public parentRegistrar;
// The event emitter
IZNSHub public zNSHub;
uint8 private test; // ignore
uint256 private gap; // ignore
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
modifier onlyController() {
if (!controllers[msg.sender] && !zNSHub.isController(msg.sender)) {
revert("ZR: Not controller");
}
_;
}
modifier onlyOwnerOf(uint256 id) {
require(ownerOf(id) == msg.sender, "ZR: Not owner");
_;
}
function initialize(
address parentRegistrar_,
uint256 rootDomainId_,
string calldata collectionName,
string calldata collectionSymbol,
address zNSHub_
) public initializer {
// __Ownable_init(); // Purposely not initializing ownable since we override owner()
if (parentRegistrar_ == address(0)) {
// create the root domain
_createDomain(0, 0, msg.sender, address(0));
} else {
rootDomainId = rootDomainId_;
parentRegistrar = parentRegistrar_;
}
zNSHub = IZNSHub(zNSHub_);
__ERC721Pausable_init();
__ERC721_init(collectionName, collectionSymbol);
}
// Used to upgrade existing registrar to new registrar
function upgradeFromNormalRegistrar(address zNSHub_) public {
require(msg.sender == _getAdmin(), "Not Proxy Admin");
zNSHub = IZNSHub(zNSHub_);
}
function owner() public view override returns (address) {
return zNSHub.owner();
}
/*
* External Methods
*/
/**
* @notice Authorizes a controller to control the registrar
* @param controller The address of the controller
*/
function addController(address controller) external {
require(
msg.sender == owner() || msg.sender == parentRegistrar,
"ZR: Not authorized"
);
require(!controllers[controller], "ZR: Controller is already added");
controllers[controller] = true;
emit ControllerAdded(controller);
}
/**
* @notice Unauthorizes a controller to control the registrar
* @param controller The address of the controller
*/
function removeController(address controller) external override onlyOwner {
require(
msg.sender == owner() || msg.sender == parentRegistrar,
"ZR: Not authorized"
);
require(controllers[controller], "ZR: Controller does not exist");
controllers[controller] = false;
emit ControllerRemoved(controller);
}
/**
* @notice Pauses the registrar. Can only be done when not paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses the registrar. Can only be done when not paused.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Registers a new (sub) domain
* @param parentId The parent domain
* @param label The label of the domain
* @param minter the minter of the new domain
* @param metadataUri The uri of the metadata
* @param royaltyAmount The amount of royalty this domain pays
* @param locked Whether the domain is locked or not
*/
function registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) external override onlyController returns (uint256) {
return
_registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
}
function registerDomainAndSend(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external override onlyController returns (uint256) {
// Register the domain
uint256 id = _registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
// immediately send domain to user
_safeTransfer(minter, sendToUser, id, "");
return id;
}
function registerSubdomainContract(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external onlyController returns (uint256) {
// Register domain, `minter` is the minter
uint256 id = _registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
// Create subdomain contract as a beacon proxy
address subdomainContract = address(
new BeaconProxy(zNSHub.registrarBeacon(), "")
);
// More maintainable instead of using `data` in constructor
Registrar(subdomainContract).initialize(
address(this),
id,
"Zer0 Name Service",
"ZNS",
address(zNSHub)
);
// Indicate that the subdomain has a contract
records[id].subdomainContract = subdomainContract;
zNSHub.addRegistrar(id, subdomainContract);
// immediately send the domain to the user (from the minter)
_safeTransfer(minter, sendToUser, id, "");
return id;
}
function _registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) internal returns (uint256) {
require(bytes(label).length > 0, "ZR: Empty name");
// subdomain cannot be minted on domains which are subdomain contracts
require(
records[parentId].subdomainContract == address(0),
"ZR: Parent is subcontract"
);
if (parentId != rootDomainId) {
// Domain parents must exist
require(_exists(parentId), "ZR: No parent");
}
// Create the child domain under the parent domain
uint256 labelHash = uint256(keccak256(bytes(label)));
address controller = msg.sender;
// Calculate the new domain's id and create it
uint256 domainId = uint256(
keccak256(abi.encodePacked(parentId, labelHash))
);
_createDomain(parentId, domainId, minter, controller);
_setTokenURI(domainId, metadataUri);
if (locked) {
records[domainId].metadataLockedBy = minter;
records[domainId].metadataLocked = true;
}
if (royaltyAmount > 0) {
records[domainId].royaltyAmount = royaltyAmount;
}
zNSHub.domainCreated(
domainId,
label,
labelHash,
parentId,
minter,
controller,
metadataUri,
royaltyAmount
);
return domainId;
}
/**
* @notice Sets the domain royalty amount
* @param id The domain to set on
* @param amount The royalty amount
*/
function setDomainRoyaltyAmount(uint256 id, uint256 amount)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
records[id].royaltyAmount = amount;
zNSHub.royaltiesAmountChanged(id, amount);
}
/**
* @notice Both sets and locks domain metadata uri in a single call
* @param id The domain to lock
* @param uri The uri to set
*/
function setAndLockDomainMetadata(uint256 id, string memory uri)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
_setDomainMetadataUri(id, uri);
_setDomainLock(id, msg.sender, true);
}
/**
* @notice Sets the domain metadata uri
* @param id The domain to set on
* @param uri The uri to set
*/
function setDomainMetadataUri(uint256 id, string memory uri)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
_setDomainMetadataUri(id, uri);
}
/**
* @notice Locks a domains metadata uri
* @param id The domain to lock
* @param toLock whether the domain should be locked or not
*/
function lockDomainMetadata(uint256 id, bool toLock) external override {
_validateLockDomainMetadata(id, toLock);
_setDomainLock(id, msg.sender, toLock);
}
/*
* Public View
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override(ERC721Upgradeable, IERC721Upgradeable)
returns (address)
{
// Check if the token is in this contract
if (_tokenOwners.contains(tokenId)) {
return
_tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
return zNSHub.ownerOf(tokenId);
}
/**
* @notice Returns whether or not an account is a a controller registered on this contract
* @param account Address of account to check
*/
function isController(address account) external view override returns (bool) {
bool accountIsController = controllers[account];
return accountIsController;
}
/**
* @notice Returns whether or not a domain is exists
* @param id The domain
*/
function domainExists(uint256 id) public view override returns (bool) {
bool domainNftExists = _exists(id);
return domainNftExists;
}
/**
* @notice Returns the original minter of a domain
* @param id The domain
*/
function minterOf(uint256 id) public view override returns (address) {
address minter = records[id].minter;
return minter;
}
/**
* @notice Returns whether or not a domain's metadata is locked
* @param id The domain
*/
function isDomainMetadataLocked(uint256 id)
public
view
override
returns (bool)
{
bool isLocked = records[id].metadataLocked;
return isLocked;
}
/**
* @notice Returns who locked a domain's metadata
* @param id The domain
*/
function domainMetadataLockedBy(uint256 id)
public
view
override
returns (address)
{
address lockedBy = records[id].metadataLockedBy;
return lockedBy;
}
/**
* @notice Returns the controller which created the domain on behalf of a user
* @param id The domain
*/
function domainController(uint256 id) public view override returns (address) {
address controller = records[id].controller;
return controller;
}
/**
* @notice Returns the current royalty amount for a domain
* @param id The domain
*/
function domainRoyaltyAmount(uint256 id)
public
view
override
returns (uint256)
{
uint256 amount = records[id].royaltyAmount;
return amount;
}
/**
* @notice Returns the parent id of a domain.
* @param id The domain
*/
function parentOf(uint256 id) public view override returns (uint256) {
require(_exists(id), "ZR: Does not exist");
uint256 parentId = records[id].parentId;
return parentId;
}
/*
* Internal Methods
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._transfer(from, to, tokenId);
// Need to emit transfer events on event emitter
zNSHub.domainTransferred(from, to, tokenId);
}
function _setDomainMetadataUri(uint256 id, string memory uri) internal {
_setTokenURI(id, uri);
zNSHub.metadataChanged(id, uri);
}
function _validateLockDomainMetadata(uint256 id, bool toLock) internal view {
if (toLock) {
require(ownerOf(id) == msg.sender, "ZR: Not owner");
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
} else {
require(isDomainMetadataLocked(id), "ZR: Not locked");
require(domainMetadataLockedBy(id) == msg.sender, "ZR: Not locker");
}
}
// internal - creates a domain
function _createDomain(
uint256 parentId,
uint256 domainId,
address minter,
address controller
) internal {
// Create the NFT and register the domain data
_mint(minter, domainId);
records[domainId] = DomainRecord({
parentId: parentId,
minter: minter,
metadataLocked: false,
metadataLockedBy: address(0),
controller: controller,
royaltyAmount: 0,
subdomainContract: address(0)
});
}
function _setDomainLock(
uint256 id,
address locker,
bool lockStatus
) internal {
records[id].metadataLockedBy = locker;
records[id].metadataLocked = lockStatus;
zNSHub.metadataLockChanged(id, locker, lockStatus);
}
function adminBurnToken(uint256 tokenId) external onlyOwner {
_burn(tokenId);
delete (records[tokenId]);
}
function adminTransfer(
address from,
address to,
uint256 tokenId
) external onlyOwner {
_transfer(from, to, tokenId);
}
function adminSetMetadataUri(uint256 id, string memory uri)
external
onlyOwner
{
_setDomainMetadataUri(id, uri);
}
function registerDomainAndSendBulk(
uint256 parentId,
uint256 namingOffset, // e.g., the IPFS node refers to the metadata as x. the zNS label will be x + namingOffset
uint256 startingIndex,
uint256 endingIndex,
address minter,
string memory folderWithIPFSPrefix, // e.g., ipfs://Qm.../
uint256 royaltyAmount,
bool locked
) external onlyController {
require(endingIndex - startingIndex > 0, "Invalid number of domains");
uint256 result;
for (uint256 i = startingIndex; i < endingIndex; i++) {
result = _registerDomain(
parentId,
uint2str(i + namingOffset),
minter,
string(abi.encodePacked(folderWithIPFSPrefix, uint2str(i))),
royaltyAmount,
locked
);
}
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ERC721Upgradeable.sol";
import "../../utils/PausableUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev ERC721 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.
*/
abstract contract ERC721PausableUpgradeable is
Initializable,
ERC721Upgradeable,
PausableUpgradeable
{
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../oz/token/ERC721/IERC721EnumerableUpgradeable.sol";
import "../oz/token/ERC721/IERC721MetadataUpgradeable.sol";
interface IRegistrar is
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
// Emitted when a controller is removed
event ControllerAdded(address indexed controller);
// Emitted whenever a controller is removed
event ControllerRemoved(address indexed controller);
// Emitted whenever a new domain is created
event DomainCreated(
uint256 indexed id,
string label,
uint256 indexed labelHash,
uint256 indexed parent,
address minter,
address controller,
string metadataUri,
uint256 royaltyAmount
);
// Emitted whenever the metadata of a domain is locked
event MetadataLockChanged(uint256 indexed id, address locker, bool isLocked);
// Emitted whenever the metadata of a domain is changed
event MetadataChanged(uint256 indexed id, string uri);
// Emitted whenever the royalty amount is changed
event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount);
// Authorises a controller, who can register domains.
function addController(address controller) external;
// Revoke controller permission for an address.
function removeController(address controller) external;
// Registers a new sub domain
function registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) external returns (uint256);
function registerDomainAndSend(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external returns (uint256);
function registerSubdomainContract(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external returns (uint256);
// Set a domains metadata uri and lock that domain from being modified
function setAndLockDomainMetadata(uint256 id, string memory uri) external;
// Lock a domain's metadata so that it cannot be changed
function lockDomainMetadata(uint256 id, bool toLock) external;
// Update a domain's metadata uri
function setDomainMetadataUri(uint256 id, string memory uri) external;
// Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places)
function setDomainRoyaltyAmount(uint256 id, uint256 amount) external;
// Returns whether an address is a controller
function isController(address account) external view returns (bool);
// Checks whether or not a domain exists
function domainExists(uint256 id) external view returns (bool);
// Returns the original minter of a domain
function minterOf(uint256 id) external view returns (address);
// Checks if a domains metadata is locked
function isDomainMetadataLocked(uint256 id) external view returns (bool);
// Returns the address which locked the domain metadata
function domainMetadataLockedBy(uint256 id) external view returns (address);
// Gets the controller that registered a domain
function domainController(uint256 id) external view returns (address);
// Gets a domains current royalty amount
function domainRoyaltyAmount(uint256 id) external view returns (uint256);
// Returns the parent domain of a child domain
function parentOf(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot)
internal
pure
returns (AddressSlot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot)
internal
pure
returns (BooleanSlot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot)
internal
pure
returns (Bytes32Slot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot)
internal
pure
returns (Uint256Slot storage r)
{
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
assert(
_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)
);
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import {IRegistrar} from "./IRegistrar.sol";
interface IZNSHub {
function addRegistrar(uint256 rootDomainId, address registrar) external;
function isController(address controller) external returns (bool);
function getRegistrarForDomain(uint256 domainId)
external
view
returns (IRegistrar);
function ownerOf(uint256 domainId) external view returns (address);
function domainExists(uint256 domainId) external view returns (bool);
function owner() external view returns (address);
function registrarBeacon() external view returns (address);
function domainTransferred(
address from,
address to,
uint256 tokenId
) external;
function domainCreated(
uint256 id,
string calldata name,
uint256 nameHash,
uint256 parent,
address minter,
address controller,
string calldata metadataUri,
uint256 royaltyAmount
) external;
function metadataLockChanged(
uint256 id,
address locker,
bool isLocked
) external;
function metadataChanged(uint256 id, string calldata uri) external;
function royaltiesAmountChanged(uint256 id, uint256 amount) external;
// Returns the parent domain of a child domain
function parentOf(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.9;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
_initializing || _isConstructor() || !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is
Initializable,
ContextUpgradeable,
ERC165Upgradeable,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap internal _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_)
internal
initializer
{
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_)
internal
initializer
{
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721Upgradeable.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @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(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (
bytes32 slot
) {
require(
slot == _IMPLEMENTATION_SLOT,
"ERC1967Upgrade: unsupported proxiableUUID"
);
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
Address.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | 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);
}
| 143,831 |
./full_match/80001/0xdBAf7190865A37E0E92e1554807CeA075eec3174/sources/contracts/Edition.sol | Updates the external_url field in the metadata can be updated by the owner regardless of the grace period log the current external url | function setExternalUrl(string calldata _externalUrl) public onlyOwner {
emit ExternalUrlUpdated(externalUrl, _externalUrl);
externalUrl = _externalUrl;
}
| 873,673 |
./full_match/80001/0xc04e87bCd09B1821db562fc2f5748DD193713a67/sources/_superfluid-finance/ethereum-contracts/contracts/apps/CFAv1Library.sol | Create/update/delete flow with context cfaLibrary The cfaLibrary storage variable ctx Context bytes (see ISuperfluid.sol for Context struct) receiver The receiver of the flow token The token to flow flowRate The desired flowRate/ | function flowWithCtx(
InitData storage cfaLibrary,
bytes memory ctx,
address receiver,
ISuperfluidToken token,
int96 flowRate
) internal returns (bytes memory newCtx) {
if ( flowRate == int96(0) ) {
return deleteFlowWithCtx(cfaLibrary, ctx, address(this), receiver, token);
(,int96 existingFlowRate,,) = cfaLibrary.cfa.getFlow(token, address(this), receiver);
if ( existingFlowRate == int96(0) ) {
return createFlowWithCtx(cfaLibrary, ctx, receiver, token, flowRate);
return updateFlowWithCtx(cfaLibrary, ctx, receiver, token, flowRate);
}
}
}
| 9,464,115 |
./partial_match/1/0x2101b79baE6B9BA590Aa5960F0ecBA2320968a60/sources/HalfPepe.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Half Pepe", "PEPE0.5") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), PEPE);
excludeFromMaxTransaction(address(uniswapV2Pair), true);
uint256 _buyDevFee = 20;
uint256 _buyLiquidityFee = 0;
uint256 _sellDevFee = 20;
uint256 _sellLiquidityFee = 0;
uint256 totalSupply = 1_000_000 * 1e18;
buyDevFee = _buyDevFee;
buyLiquidityFee = _buyLiquidityFee;
buyTotalFees = buyDevFee + buyLiquidityFee;
sellDevFee = _sellDevFee;
sellLiquidityFee = _sellLiquidityFee;
sellTotalFees = sellDevFee + sellLiquidityFee;
devWallet = address(0x339c25E1C1386366F057Eb54a383d5C9eab2B168);
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);
| 9,400,820 |
./full_match/1/0xb867dF3efF1B234CA08B7D0d85Fb51Fd25C2c2d0/sources/contracts/v2/strategies/RamosStrategy.sol | The latest checkpoint of each asset balance this strategy holds, and the current debt. This will be used to report equity performance: `sum(asset value in STABLE) - debt` The conversion of each asset price into the stable token (eg DAI) will be done off-chain The asset value may be stale at any point in time, depending on the strategy. It may optionally implement `checkpointAssetBalances()` in order to update those balances./ get RAMOS's quote token balance | function latestAssetBalances() public override view returns (
AssetBalance[] memory assetBalances
) {
(,, uint256 quoteTokenBalance) = ramos.positions();
assetBalances = new AssetBalance[](1);
assetBalances[0] = AssetBalance({
asset: address(quoteToken),
balance: quoteTokenBalance
});
}
| 3,120,043 |
./full_match/11155111/0x518D3f7281d8686512Fa680696922Ad3394D1d82/sources/contracts/EHealth.sol | Function for doctors to access patient data and provide suggestions | function provideMedicalSuggestion(
address _patientAddress,
address _doctorAddress,
string memory _suggestion
) public {
require(bytes(_suggestion).length > 0, "Suggestion is required");
require(
_containsPatient(_doctorAddress, _patientAddress),
"You are not authorized to access this patient's data"
);
require(
patients[_getPatientIdFromAddress(_patientAddress)]
.doctorAddr == _doctorAddress,
"You are not authorized to give suggestion to this patient"
);
patients[_getPatientIdFromAddress(_patientAddress)]
.suggestion = _suggestion;
}
| 3,794,711 |
pragma solidity ^0.4.13;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// require(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// require(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) {
require(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;
require(c >= a);
return c;
}
}
contract ERC20 {
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] = SafeMath.sub(allowance[_from][msg.sender], _value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* ######################
* # private function #
* ######################
*/
function _transfer(address _from, address _to, uint _value) internal {
require(balanceOf[_from] >= _value);
require(SafeMath.add(balanceOf[_to], _value) >= balanceOf[_to]);
balanceOf[_from] = SafeMath.sub(balanceOf[_from], _value);
balanceOf[_to] = SafeMath.add(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
}
}
contract Token is ERC20 {
uint8 public constant decimals = 9;
uint256 public constant initialSupply = 10 * (10 ** 8) * (10 ** uint256(decimals));
string public constant name = 'INK Coin';
string public constant symbol = 'INK';
function() public {
revert();
}
function Token() public {
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
if (approve(_spender, _value)) {
if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) {
revert();
}
return true;
}
}
}
interface XCInterface {
/**
* Set contract service status.
* @param status contract service status (0:closed;1:only-closed-lock;2:only-closed-unlock;3:opened;).
*/
function setStatus(uint8 status) external;
/**
* Get contract service status.
* @return contract service status.
*/
function getStatus() external view returns (uint8);
/**
* Get the current contract platform name.
* @return contract platform name.
*/
function getPlatformName() external view returns (bytes32);
/**
* Set the current contract administrator.
* @param account account of contract administrator.
*/
function setAdmin(address account) external;
/**
* Get the current contract administrator.
* @return contract administrator.
*/
function getAdmin() external view returns (address);
/**
* Set the Token contract address.
* @param account contract address.
*/
function setToken(address account) external;
/**
* Get the Token contract address.
* @return contract address.
*/
function getToken() external view returns (address);
/**
* Set the XCPlugin contract address.
* @param account contract address.
*/
function setXCPlugin(address account) external;
/**
* Get the XCPlugin contract address.
* @return contract address.
*/
function getXCPlugin() external view returns (address);
/**
* Set the comparison symbol in the contract.
* @param symbol comparison symbol ({"-=" : ">" , "+=" : ">=" }).
*/
function setCompare(bytes2 symbol) external;
/**
* Get the comparison symbol in the contract.
* @return comparison symbol.
*/
function getCompare() external view returns (bytes2);
/**
* Transfer out of cross chain.
* @param toPlatform name of to platform.
* @param toAccount account of to platform.
* @param value transfer amount.
*/
function lock(bytes32 toPlatform, address toAccount, uint value) external payable;
/**
* Transfer in of cross chain.
* @param txid transaction id.
* @param fromPlatform name of form platform.
* @param fromAccount ame of to platform.
* @param toAccount account of to platform.
* @param value transfer amount.
*/
function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable;
/**
* Transfer the misoperation to the amount of the contract account to the specified account.
* @param account the specified account.
* @param value transfer amount.
*/
function withdraw(address account, uint value) external payable;
/**
* Transfer the money(qtum/eth) from the contract account.
* @param account the specified account.
* @param value transfer amount.
*/
function transfer(address account, uint value) external payable;
/**
* Deposit money(eth) into a contract.
*/
function deposit() external payable;
}
contract XC is XCInterface {
/**
* Contract Administrator
* @field status Contract external service status.
* @field platformName Current contract platform name.
* @field account Current contract administrator.
*/
struct Admin {
uint8 status;
bytes32 platformName;
bytes32 tokenSymbol;
bytes2 compareSymbol;
address account;
}
Admin private admin;
uint public lockBalance;
Token private token;
XCPlugin private xcPlugin;
event Lock(bytes32 toPlatform, address toAccount, bytes32 value, bytes32 tokenSymbol);
event Unlock(string txid, bytes32 fromPlatform, address fromAccount, bytes32 value, bytes32 tokenSymbol);
event Deposit(address from, bytes32 value);
function XC() public payable {
init();
}
function init() internal {
// Admin {status | platformName | tokenSymbol | compareSymbol | account}
admin.status = 3;
admin.platformName = "ETH";
admin.tokenSymbol = "INK";
admin.compareSymbol = "+=";
admin.account = msg.sender;
//totalSupply = 10 * (10 ** 8) * (10 ** 9);
lockBalance = 10 * (10 ** 8) * (10 ** 9);
token = Token(0xc15d8f30fa3137eee6be111c2933f1624972f45c);
xcPlugin = XCPlugin(0x55c87c2e26f66fd3642645c3f25c9e81a75ec0f4);
}
function setStatus(uint8 status) external {
require(admin.account == msg.sender);
require(status == 0 || status == 1 || status == 2 || status == 3);
if (admin.status != status) {
admin.status = status;
}
}
function getStatus() external view returns (uint8) {
return admin.status;
}
function getPlatformName() external view returns (bytes32) {
return admin.platformName;
}
function setAdmin(address account) external {
require(account != address(0));
require(admin.account == msg.sender);
if (admin.account != account) {
admin.account = account;
}
}
function getAdmin() external view returns (address) {
return admin.account;
}
function setToken(address account) external {
require(admin.account == msg.sender);
if (token != account) {
token = Token(account);
}
}
function getToken() external view returns (address) {
return token;
}
function setXCPlugin(address account) external {
require(admin.account == msg.sender);
if (xcPlugin != account) {
xcPlugin = XCPlugin(account);
}
}
function getXCPlugin() external view returns (address) {
return xcPlugin;
}
function setCompare(bytes2 symbol) external {
require(admin.account == msg.sender);
require(symbol == "+=" || symbol == "-=");
if (admin.compareSymbol != symbol) {
admin.compareSymbol = symbol;
}
}
function getCompare() external view returns (bytes2){
require(admin.account == msg.sender);
return admin.compareSymbol;
}
function lock(bytes32 toPlatform, address toAccount, uint value) external payable {
require(admin.status == 2 || admin.status == 3);
require(xcPlugin.getStatus());
require(xcPlugin.existPlatform(toPlatform));
require(toAccount != address(0));
// require(token.totalSupply >= value && value > 0);
require(value > 0);
//get user approve the contract quota
uint allowance = token.allowance(msg.sender, this);
require(toCompare(allowance, value));
//do transferFrom
bool success = token.transferFrom(msg.sender, this, value);
require(success);
//record the amount of local platform turn out
lockBalance = SafeMath.add(lockBalance, value);
// require(token.totalSupply >= lockBalance);
//trigger Lock
emit Lock(toPlatform, toAccount, bytes32(value), admin.tokenSymbol);
}
function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable {
require(admin.status == 1 || admin.status == 3);
require(xcPlugin.getStatus());
require(xcPlugin.existPlatform(fromPlatform));
require(toAccount != address(0));
// require(token.totalSupply >= value && value > 0);
require(value > 0);
//verify args by function xcPlugin.verify
bool complete;
bool verify;
(complete, verify) = xcPlugin.verifyProposal(fromPlatform, fromAccount, toAccount, value, admin.tokenSymbol, txid);
require(verify && !complete);
//get contracts balance
uint balance = token.balanceOf(this);
//validate the balance of contract were less than amount
require(toCompare(balance, value));
require(token.transfer(toAccount, value));
require(xcPlugin.commitProposal(fromPlatform, txid));
lockBalance = SafeMath.sub(lockBalance, value);
emit Unlock(txid, fromPlatform, fromAccount, bytes32(value), admin.tokenSymbol);
}
function withdraw(address account, uint value) external payable {
require(admin.account == msg.sender);
require(account != address(0));
// require(token.totalSupply >= value && value > 0);
require(value > 0);
uint balance = token.balanceOf(this);
require(toCompare(SafeMath.sub(balance, lockBalance), value));
bool success = token.transfer(account, value);
require(success);
}
function transfer(address account, uint value) external payable {
require(admin.account == msg.sender);
require(account != address(0));
require(value > 0 && value >= address(this).balance);
this.transfer(account, value);
}
function deposit() external payable {
emit Deposit(msg.sender, bytes32(msg.value));
}
/**
* ######################
* # private function #
* ######################
*/
function toCompare(uint f, uint s) internal view returns (bool) {
if (admin.compareSymbol == "-=") {
return f > s;
} else if (admin.compareSymbol == "+=") {
return f >= s;
} else {
return false;
}
}
}
interface XCPluginInterface {
/**
* Open the contract service status.
*/
function start() external;
/**
* Close the contract service status.
*/
function stop() external;
/**
* Get contract service status.
* @return contract service status.
*/
function getStatus() external view returns (bool);
/**
* Get the current contract platform name.
* @return contract platform name.
*/
function getPlatformName() external view returns (bytes32);
/**
* Set the current contract administrator.
* @param account account of contract administrator.
*/
function setAdmin(address account) external;
/**
* Get the current contract administrator.
* @return contract administrator.
*/
function getAdmin() external view returns (address);
/**
* Add a contract trust caller.
* @param caller account of caller.
*/
function addCaller(address caller) external;
/**
* Delete a contract trust caller.
* @param caller account of caller.
*/
function deleteCaller(address caller) external;
/**
* Whether the trust caller exists.
* @param caller account of caller.
* @return whether exists.
*/
function existCaller(address caller) external view returns (bool);
/**
* Get all contract trusted callers.
* @return al lcallers.
*/
function getCallers() external view returns (address[]);
/**
* Add a trusted platform name.
* @param name a platform name.
*/
function addPlatform(bytes32 name) external;
/**
* Delete a trusted platform name.
* @param name a platform name.
*/
function deletePlatform(bytes32 name) external;
/**
* Whether the trusted platform information exists.
* @param name a platform name.
* @return whether exists.
*/
function existPlatform(bytes32 name) external view returns (bool);
/**
* Add the trusted platform public key information.
* @param platformName a platform name.
* @param publicKey a public key.
*/
function addPublicKey(bytes32 platformName, address publicKey) external;
/**
* Delete the trusted platform public key information.
* @param platformName a platform name.
* @param publicKey a public key.
*/
function deletePublicKey(bytes32 platformName, address publicKey) external;
/**
* Whether the trusted platform public key information exists.
* @param platformName a platform name.
* @param publicKey a public key.
*/
function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool);
/**
* Get the count of public key for the trusted platform.
* @param platformName a platform name.
* @return count of public key.
*/
function countOfPublicKey(bytes32 platformName) external view returns (uint);
/**
* Get the list of public key for the trusted platform.
* @param platformName a platform name.
* @return list of public key.
*/
function publicKeys(bytes32 platformName) external view returns (address[]);
/**
* Set the weight of a trusted platform.
* @param platformName a platform name.
* @param weight weight of platform.
*/
function setWeight(bytes32 platformName, uint weight) external;
/**
* Get the weight of a trusted platform.
* @param platformName a platform name.
* @return weight of platform.
*/
function getWeight(bytes32 platformName) external view returns (uint);
/**
* Initiate and vote on the transaction proposal.
* @param fromPlatform name of form platform.
* @param fromAccount name of to platform.
* @param toAccount account of to platform.
* @param value transfer amount.
* @param tokenSymbol token Symbol.
* @param txid transaction id.
* @param sig transaction signature.
*/
function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external;
/**
* Verify that the transaction proposal is valid.
* @param fromPlatform name of form platform.
* @param fromAccount name of to platform.
* @param toAccount account of to platform.
* @param value transfer amount.
* @param tokenSymbol token Symbol.
* @param txid transaction id.
*/
function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool);
/**
* Commit the transaction proposal.
* @param platformName a platform name.
* @param txid transaction id.
*/
function commitProposal(bytes32 platformName, string txid) external returns (bool);
/**
* Get the transaction proposal information.
* @param platformName a platform name.
* @param txid transaction id.
* @return status completion status of proposal.
* @return fromAccount account of to platform.
* @return toAccount account of to platform.
* @return value transfer amount.
* @return voters notarial voters.
* @return weight The weight value of the completed time.
*/
function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight);
/**
* Delete the transaction proposal information.
* @param platformName a platform name.
* @param txid transaction id.
*/
function deleteProposal(bytes32 platformName, string txid) external;
/**
* Transfer the money(qtum/eth) from the contract account.
* @param account the specified account.
* @param value transfer amount.
*/
function transfer(address account, uint value) external payable;
}
contract XCPlugin is XCPluginInterface {
/**
* Contract Administrator
* @field status Contract external service status.
* @field platformName Current contract platform name.
* @field tokenSymbol token Symbol.
* @field account Current contract administrator.
*/
struct Admin {
bool status;
bytes32 platformName;
bytes32 tokenSymbol;
address account;
}
/**
* Transaction Proposal
* @field status Transaction proposal status(false:pending,true:complete).
* @field fromAccount Account of form platform.
* @field toAccount Account of to platform.
* @field value Transfer amount.
* @field tokenSymbol token Symbol.
* @field voters Proposers.
* @field weight The weight value of the completed time.
*/
struct Proposal {
bool status;
address fromAccount;
address toAccount;
uint value;
bytes32 tokenSymbol;
address[] voters;
uint weight;
}
/**
* Trusted Platform
* @field status Trusted platform state(false:no trusted,true:trusted).
* @field weight weight of platform.
* @field publicKeys list of public key.
* @field proposals list of proposal.
*/
struct Platform {
bool status;
uint weight;
address[] publicKeys;
mapping(string => Proposal) proposals;
}
Admin private admin;
address[] private callers;
mapping(bytes32 => Platform) private platforms;
function XCPlugin() public {
init();
}
function init() internal {
// Admin { status | platformName | tokenSymbol | account}
admin.status = true;
admin.platformName = "ETH";
admin.tokenSymbol = "INK";
admin.account = msg.sender;
bytes32 platformName = "INK";
platforms[platformName].status = true;
platforms[platformName].weight = 1;
platforms[platformName].publicKeys.push(0x4230a12f5b0693dd88bb35c79d7e56a68614b199);
platforms[platformName].publicKeys.push(0x07caf88941eafcaaa3370657fccc261acb75dfba);
}
function start() external {
require(admin.account == msg.sender);
if (!admin.status) {
admin.status = true;
}
}
function stop() external {
require(admin.account == msg.sender);
if (admin.status) {
admin.status = false;
}
}
function getStatus() external view returns (bool) {
return admin.status;
}
function getPlatformName() external view returns (bytes32) {
return admin.platformName;
}
function setAdmin(address account) external {
require(account != address(0));
require(admin.account == msg.sender);
if (admin.account != account) {
admin.account = account;
}
}
function getAdmin() external view returns (address) {
return admin.account;
}
function addCaller(address caller) external {
require(admin.account == msg.sender);
if (!_existCaller(caller)) {
callers.push(caller);
}
}
function deleteCaller(address caller) external {
require(admin.account == msg.sender);
if (_existCaller(caller)) {
bool exist;
for (uint i = 0; i <= callers.length; i++) {
if (exist) {
if (i == callers.length) {
delete callers[i - 1];
callers.length--;
} else {
callers[i - 1] = callers[i];
}
} else if (callers[i] == caller) {
exist = true;
}
}
}
}
function existCaller(address caller) external view returns (bool) {
return _existCaller(caller);
}
function getCallers() external view returns (address[]) {
require(admin.account == msg.sender);
return callers;
}
function addPlatform(bytes32 name) external {
require(admin.account == msg.sender);
require(name != "");
require(name != admin.platformName);
if (!_existPlatform(name)) {
platforms[name].status = true;
if (platforms[name].weight == 0) {
platforms[name].weight = 1;
}
}
}
function deletePlatform(bytes32 name) external {
require(admin.account == msg.sender);
require(name != admin.platformName);
if (_existPlatform(name)) {
platforms[name].status = false;
}
}
function existPlatform(bytes32 name) external view returns (bool){
return _existPlatform(name);
}
function setWeight(bytes32 platformName, uint weight) external {
require(admin.account == msg.sender);
require(_existPlatform(platformName));
require(weight > 0);
if (platforms[platformName].weight != weight) {
platforms[platformName].weight = weight;
}
}
function getWeight(bytes32 platformName) external view returns (uint) {
require(admin.account == msg.sender);
require(_existPlatform(platformName));
return platforms[platformName].weight;
}
function addPublicKey(bytes32 platformName, address publicKey) external {
require(admin.account == msg.sender);
require(_existPlatform(platformName));
require(publicKey != address(0));
address[] storage listOfPublicKey = platforms[platformName].publicKeys;
for (uint i; i < listOfPublicKey.length; i++) {
if (publicKey == listOfPublicKey[i]) {
return;
}
}
listOfPublicKey.push(publicKey);
}
function deletePublicKey(bytes32 platformName, address publickey) external {
require(admin.account == msg.sender);
require(_existPlatform(platformName));
address[] storage listOfPublicKey = platforms[platformName].publicKeys;
bool exist;
for (uint i = 0; i <= listOfPublicKey.length; i++) {
if (exist) {
if (i == listOfPublicKey.length) {
delete listOfPublicKey[i - 1];
listOfPublicKey.length--;
} else {
listOfPublicKey[i - 1] = listOfPublicKey[i];
}
} else if (listOfPublicKey[i] == publickey) {
exist = true;
}
}
}
function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool) {
require(admin.account == msg.sender);
return _existPublicKey(platformName, publicKey);
}
function countOfPublicKey(bytes32 platformName) external view returns (uint){
require(admin.account == msg.sender);
require(_existPlatform(platformName));
return platforms[platformName].publicKeys.length;
}
function publicKeys(bytes32 platformName) external view returns (address[]){
require(admin.account == msg.sender);
require(_existPlatform(platformName));
return platforms[platformName].publicKeys;
}
function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external {
require(admin.status);
require(_existPlatform(fromPlatform));
bytes32 msgHash = hashMsg(fromPlatform, fromAccount, admin.platformName, toAccount, value, tokenSymbol, txid);
// address publicKey = ecrecover(msgHash, v, r, s);
address publicKey = recover(msgHash, sig);
require(_existPublicKey(fromPlatform, publicKey));
Proposal storage proposal = platforms[fromPlatform].proposals[txid];
if (proposal.value == 0) {
proposal.fromAccount = fromAccount;
proposal.toAccount = toAccount;
proposal.value = value;
proposal.tokenSymbol = tokenSymbol;
} else {
require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol);
}
changeVoters(fromPlatform, publicKey, txid);
}
function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool) {
require(admin.status);
require(_existPlatform(fromPlatform));
Proposal storage proposal = platforms[fromPlatform].proposals[txid];
if (proposal.status) {
return (true, (proposal.voters.length >= proposal.weight));
}
if (proposal.value == 0) {
return (false, false);
}
require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol);
return (false, (proposal.voters.length >= platforms[fromPlatform].weight));
}
function commitProposal(bytes32 platformName, string txid) external returns (bool) {
require(admin.status);
require(_existCaller(msg.sender) || msg.sender == admin.account);
require(_existPlatform(platformName));
require(!platforms[platformName].proposals[txid].status);
platforms[platformName].proposals[txid].status = true;
platforms[platformName].proposals[txid].weight = platforms[platformName].proposals[txid].voters.length;
return true;
}
function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight){
require(admin.status);
require(_existPlatform(platformName));
fromAccount = platforms[platformName].proposals[txid].fromAccount;
toAccount = platforms[platformName].proposals[txid].toAccount;
value = platforms[platformName].proposals[txid].value;
voters = platforms[platformName].proposals[txid].voters;
status = platforms[platformName].proposals[txid].status;
weight = platforms[platformName].proposals[txid].weight;
return;
}
function deleteProposal(bytes32 platformName, string txid) external {
require(msg.sender == admin.account);
require(_existPlatform(platformName));
delete platforms[platformName].proposals[txid];
}
function transfer(address account, uint value) external payable {
require(admin.account == msg.sender);
require(account != address(0));
require(value > 0 && value >= address(this).balance);
this.transfer(account, value);
}
/**
* ######################
* # private function #
* ######################
*/
function hashMsg(bytes32 fromPlatform, address fromAccount, bytes32 toPlatform, address toAccount, uint value, bytes32 tokenSymbol, string txid) internal pure returns (bytes32) {
return sha256(bytes32ToStr(fromPlatform), ":0x", uintToStr(uint160(fromAccount), 16), ":", bytes32ToStr(toPlatform), ":0x", uintToStr(uint160(toAccount), 16), ":", uintToStr(value, 10), ":", bytes32ToStr(tokenSymbol), ":", txid);
}
function changeVoters(bytes32 platformName, address publicKey, string txid) internal {
address[] storage voters = platforms[platformName].proposals[txid].voters;
bool change = true;
for (uint i = 0; i < voters.length; i++) {
if (voters[i] == publicKey) {
change = false;
}
}
if (change) {
voters.push(publicKey);
}
}
function bytes32ToStr(bytes32 b) internal pure returns (string) {
uint length = b.length;
for (uint i = 0; i < b.length; i++) {
if (b[b.length - 1 - i] == "") {
length -= 1;
} else {
break;
}
}
bytes memory bs = new bytes(length);
for (uint j = 0; j < length; j++) {
bs[j] = b[j];
}
return string(bs);
}
function uintToStr(uint value, uint base) internal pure returns (string) {
uint _value = value;
uint length = 0;
bytes16 tenStr = "0123456789abcdef";
while (true) {
if (_value > 0) {
length ++;
_value = _value / base;
} else {
break;
}
}
if (base == 16) {
length = 40;
}
bytes memory bs = new bytes(length);
for (uint i = 0; i < length; i++) {
bs[length - 1 - i] = tenStr[value % base];
value = value / base;
}
return string(bs);
}
function _existCaller(address caller) internal view returns (bool) {
for (uint i = 0; i < callers.length; i++) {
if (callers[i] == caller) {
return true;
}
}
return false;
}
function _existPlatform(bytes32 name) internal view returns (bool){
return platforms[name].status;
}
function _existPublicKey(bytes32 platformName, address publicKey) internal view returns (bool) {
address[] memory listOfPublicKey = platforms[platformName].publicKeys;
for (uint i = 0; i < listOfPublicKey.length; i++) {
if (listOfPublicKey[i] == publicKey) {
return true;
}
}
return false;
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
return ecrecover(hash, v, r, s);
}
} | require(token.totalSupply >= value && value > 0);get user approve the contract quotado transferFromrecord the amount of local platform turn out require(token.totalSupply >= lockBalance);trigger Lock | function lock(bytes32 toPlatform, address toAccount, uint value) external payable {
require(admin.status == 2 || admin.status == 3);
require(xcPlugin.getStatus());
require(xcPlugin.existPlatform(toPlatform));
require(toAccount != address(0));
require(value > 0);
uint allowance = token.allowance(msg.sender, this);
require(toCompare(allowance, value));
bool success = token.transferFrom(msg.sender, this, value);
require(success);
lockBalance = SafeMath.add(lockBalance, value);
emit Lock(toPlatform, toAccount, bytes32(value), admin.tokenSymbol);
}
| 14,619,498 |
./partial_match/1/0xFFFD3327d030160cddBe99c1b3447EcC3b413856/sources/EthSmart.sol | RECOMMENDED GAS LIMIT: 300 000 (90755 calculated by myetherwallet)/ Admins wallets adresses:/ deposit and withdrew counter for website:/ fee split:/ investors dividends:investors referrer program | function() payable external {
uint256 referralPercent = msg.value.mul(10).div(100);
uint256 advertisementPercent = msg.value.mul(7).div(100);
uint256 developerPercent = msg.value.mul(3).div(100);
referralAddress.transfer(referralPercent);
advertisementAddress.transfer(advertisementPercent);
developerAddress.transfer(developerPercent);
if (deposited[msg.sender] != 0) {
address investor = msg.sender;
uint256 depositsPercents = deposited[msg.sender].mul(5).div(100).mul(block.number-blocklock[msg.sender]).div(5900);
investor.transfer(depositsPercents);
withdrew[msg.sender] += depositsPercents;
totalWithdrew = totalWithdrew.add(depositsPercents);}
address referrer = bytesToAddress(msg.data);
if (referrer > 0x0 && referrer != msg.sender) {
referrer.transfer(referralPercent);
refearned[referrer] += referralPercent;}
blocklock[msg.sender] = block.number;
deposited[msg.sender] += msg.value;
totalDeposited = totalDeposited.add(msg.value);}
| 3,944,582 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface IUniswap {
// To convert DAI to ETH
function SWAPEXACTTOKENSFORETH436(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); //inject NONSTANDARD NAMING
// To convert ETH to YELD and burn it
function SWAPEXACTETHFORTOKENS487(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IERC20 {
function TOTALSUPPLY323() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF269(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE471(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE639(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM45(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER853(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL183(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER264() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA366() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address payable private _owner;
event OWNERSHIPTRANSFERRED175(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER264();
emit OWNERSHIPTRANSFERRED175(address(0), _owner);
}
function OWNER564() public view returns (address payable) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER780() { //inject NONSTANDARD NAMING
require(ISOWNER198(), "Ownable: caller is not the owner");
_;
}
function ISOWNER198() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER264() == _owner;
}
function RENOUNCEOWNERSHIP104() public ONLYOWNER780 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED175(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP788(address payable newOwner) public ONLYOWNER780 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP70(newOwner);
}
function _TRANSFEROWNERSHIP70(address payable newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED175(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
function TOTALSUPPLY323() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF269(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER6(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER918(_MSGSENDER264(), recipient, amount);
return true;
}
function ALLOWANCE471(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE639(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, amount);
return true;
}
function TRANSFERFROM45(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER918(sender, recipient, amount);
_APPROVE444(sender, _MSGSENDER264(), _allowances[sender][_MSGSENDER264()].SUB46(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE61(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].ADD992(addedValue));
return true;
}
function DECREASEALLOWANCE74(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].SUB46(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER918(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB46(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD992(amount);
emit TRANSFER853(sender, recipient, amount);
}
function _MINT980(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD992(amount);
_balances[account] = _balances[account].ADD992(amount);
emit TRANSFER853(address(0), account, amount);
}
function _BURN375(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB46(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB46(amount);
emit TRANSFER853(account, address(0), amount);
}
function _APPROVE444(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL183(owner, spender, amount);
}
function _BURNFROM405(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN375(account, amount);
_APPROVE444(account, _MSGSENDER264(), _allowances[account][_MSGSENDER264()].SUB46(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME61() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL851() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS917() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier NONREENTRANT890() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
library SafeMath {
function ADD992(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB46(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB46(a, b, "SafeMath: subtraction overflow");
}
function SUB46(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL613(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV312(a, b, "SafeMath: division by zero");
}
function DIV312(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD928(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD928(a, b, "SafeMath: modulo by zero");
}
function MOD928(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE515(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE559(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER60(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFER6.selector, to, value));
}
function SAFETRANSFERFROM510(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFERFROM45.selector, from, to, value));
}
function SAFEAPPROVE585(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE471(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, value));
}
function SAFEINCREASEALLOWANCE437(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE471(address(this), spender).ADD992(value);
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE12(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE471(address(this), spender).SUB46(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN106(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT42(), "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");
}
}
}
interface Compound {
function MINT570 ( uint256 mintAmount ) external returns ( uint256 ); //inject NONSTANDARD NAMING
function REDEEM919(uint256 redeemTokens) external returns (uint256); //inject NONSTANDARD NAMING
function EXCHANGERATESTORED297() external view returns (uint); //inject NONSTANDARD NAMING
}
interface Fulcrum {
function MINT570(address receiver, uint256 amount) external payable returns (uint256 mintAmount); //inject NONSTANDARD NAMING
function BURN957(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); //inject NONSTANDARD NAMING
function ASSETBALANCEOF748(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
}
interface ILendingPoolAddressesProvider {
function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING
}
interface Aave {
function DEPOSIT261(address _reserve, uint256 _amount, uint16 _referralCode) external; //inject NONSTANDARD NAMING
}
interface AToken {
function REDEEM919(uint256 amount) external; //inject NONSTANDARD NAMING
}
interface IIEarnManager {
function RECOMMEND876(address _token) external view returns ( //inject NONSTANDARD NAMING
string memory choice,
uint256 capr,
uint256 iapr,
uint256 aapr,
uint256 dapr
);
}
contract Structs {
struct Val {
uint256 value;
}
enum ActionType {
Deposit, // supply tokens
Withdraw // borrow tokens
}
enum AssetDenomination {
Wei // the amount is denominated in wei
}
enum AssetReference {
Delta // the amount is given as a delta from the current value
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
contract DyDx is Structs {
function GETACCOUNTWEI173(Info memory account, uint256 marketId) public view returns (Wei memory); //inject NONSTANDARD NAMING
function OPERATE410(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING
}
interface LendingPoolAddressesProvider {
function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE176() external view returns (address); //inject NONSTANDARD NAMING
}
contract yTUSD is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public pool;
address public token;
address public compound;
address public fulcrum;
address public aave;
address public aavePool;
address public aaveToken;
address public dydx;
uint256 public dToken;
address public apr;
address public chai;
// Add other tokens if implemented for another stablecoin
address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public tusd = 0x0000000000085d4780B73119b644AE5ecd22b376;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public retirementYeldTreasury;
IERC20 public yeldToken;
uint256 public maximumTokensToBurn = 50000 * 1e18;
// When you stake say 1000 TUSD for a day that will be your maximum
// if you stake the next time 300 TUSD your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 TUSD
mapping(bytes32 => uint256) public numberOfParticipants;
mapping(address => uint256) public depositBlockStarts;
uint256 public constant onedayinblocks32 = 6500; //inject NONSTANDARD NAMING
uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility
uint256 public constant onemillion240 = 1e6; //inject NONSTANDARD NAMING
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public provider = Lender.NONE;
constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn TUSD", "yTUSD", 18) {
token = address(0x0000000000085d4780B73119b644AE5ecd22b376);
apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081);
aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
dToken = 3;
yeldToken = IERC20(_yeldToken);
retirementYeldTreasury = _retirementYeldTreasury;
APPROVETOKEN94();
}
// To receive ETH after converting it from TUSD
function () external payable {}
function SETRETIREMENTYELDTREASURY648(address payable _treasury) public ONLYOWNER780 { //inject NONSTANDARD NAMING
retirementYeldTreasury = _treasury;
}
// In case a new uniswap router version is released
function SETUNISWAPROUTER36(address _uniswapRouter) public ONLYOWNER780 { //inject NONSTANDARD NAMING
uniswapRouter = _uniswapRouter;
}
function EXTRACTTOKENSIFSTUCK789(address _token, uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING
IERC20(_token).TRANSFER6(msg.sender, _amount);
}
function EXTRACTETHIFSTUCK584() public ONLYOWNER780 { //inject NONSTANDARD NAMING
OWNER564().transfer(address(this).balance);
}
function CHANGEYELDTOREWARDPERDAY778(uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING
yeldToRewardPerDay = _amount;
}
function GETGENERATEDYELDS438() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 blocksPassed;
if (depositBlockStarts[msg.sender] > 0) {
blocksPassed = block.number.SUB46(depositBlockStarts[msg.sender]);
} else {
blocksPassed = 0;
}
// This will work because amount is a token with 18 decimals
// Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1
// That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day
// your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since
// we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding
// For USDC and Tether gotta multiply by 1e12 since they have 6 decimals to get the proper result of YELD
uint256 ibalance = BALANCEOF269(msg.sender); // Balance of yTokens
uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply);
uint256 generatedYelds = accomulatedStablecoins.DIV312(onemillion240).MUL613(yeldToRewardPerDay.DIV312(1e18)).MUL613(blocksPassed).DIV312(onedayinblocks32);
return generatedYelds;
}
function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225() public { //inject NONSTANDARD NAMING
uint256 ibalance = BALANCEOF269(msg.sender);
uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply);
require(depositBlockStarts[msg.sender] > 0 && accomulatedStablecoins > 0, 'Must have deposited stablecoins beforehand');
uint256 generatedYelds = GETGENERATEDYELDS438();
depositBlockStarts[msg.sender] = block.number;
yeldToken.TRANSFER6(msg.sender, generatedYelds);
}
function DEPOSIT261(uint256 _amount) //inject NONSTANDARD NAMING
external
NONREENTRANT890
{
require(_amount > 0, "deposit must be greater than 0");
pool = CALCPOOLVALUEINTOKEN983();
IERC20(token).SAFETRANSFERFROM510(msg.sender, address(this), _amount);
// Yeld
if (GETGENERATEDYELDS438() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225();
depositBlockStarts[msg.sender] = block.number;
// Yeld
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.MUL613(_totalSupply)).DIV312(pool);
}
pool = CALCPOOLVALUEINTOKEN983();
_MINT980(msg.sender, shares);
REBALANCE90();
}
// Converts TUSD to ETH and returns how much ETH has been received from Uniswap
function TUSDTOETH442(uint256 _amount) internal returns(uint256) { //inject NONSTANDARD NAMING
IERC20(tusd).SAFEAPPROVE585(uniswapRouter, 0);
IERC20(tusd).SAFEAPPROVE585(uniswapRouter, _amount);
address[] memory path = new address[](2);
path[0] = tusd;
path[1] = weth;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input TUSD amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTTOKENSFORETH436(_amount, uint(0), path, address(this), now.ADD992(1800));
return amounts[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function BUYNBURN597(uint256 _ethToSwap) internal returns(uint256) { //inject NONSTANDARD NAMING
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(yeldToken);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTETHFORTOKENS487.value(_ethToSwap)(uint(0), path, address(0), now.ADD992(1800));
return amounts[1];
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW331(uint256 _shares) //inject NONSTANDARD NAMING
external
NONREENTRANT890
{
require(_shares > 0, "withdraw must be greater than 0");
uint256 ibalance = BALANCEOF269(msg.sender);
require(_shares <= ibalance, "insufficient balance");
pool = CALCPOOLVALUEINTOKEN983();
uint256 stablecoinsToWithdraw = (pool.MUL613(_shares)).DIV312(_totalSupply);
_balances[msg.sender] = _balances[msg.sender].SUB46(_shares, "redeem amount exceeds balance");
_totalSupply = _totalSupply.SUB46(_shares);
emit TRANSFER853(msg.sender, address(0), _shares);
uint256 b = IERC20(token).BALANCEOF269(address(this));
if (b < stablecoinsToWithdraw) {
_WITHDRAWSOME967(stablecoinsToWithdraw.SUB46(b));
}
// Yeld
uint256 generatedYelds = GETGENERATEDYELDS438();
// Take 1% of the amount to withdraw
uint256 onePercent = stablecoinsToWithdraw.DIV312(100);
depositBlockStarts[msg.sender] = block.number;
yeldToken.TRANSFER6(msg.sender, generatedYelds);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the TUSD earned into ETH for the protocol algorithms
uint256 stakingProfits = TUSDTOETH442(onePercent);
uint256 tokensAlreadyBurned = yeldToken.BALANCEOF269(address(0));
if (tokensAlreadyBurned < maximumTokensToBurn) {
// 98% is the 49% doubled since we already took the 50%
uint256 ethToSwap = stakingProfits.MUL613(98).DIV312(100);
// Buy and burn only applies up to 50k tokens burned
BUYNBURN597(ethToSwap);
// 1% for the Retirement Yield
uint256 retirementYeld = stakingProfits.MUL613(2).DIV312(100);
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 retirementYeld = stakingProfits;
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
}
IERC20(token).SAFETRANSFER60(msg.sender, stablecoinsToWithdraw.SUB46(onePercent));
// Yeld
pool = CALCPOOLVALUEINTOKEN983();
REBALANCE90();
}
function RECOMMEND876() public view returns (Lender) { //inject NONSTANDARD NAMING
(,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).RECOMMEND876(token);
uint256 max = 0;
if (capr > max) {
max = capr;
}
if (iapr > max) {
max = iapr;
}
if (aapr > max) {
max = aapr;
}
if (dapr > max) {
max = dapr;
}
Lender newProvider = Lender.NONE;
if (max == capr) {
newProvider = Lender.COMPOUND;
} else if (max == iapr) {
newProvider = Lender.FULCRUM;
} else if (max == aapr) {
newProvider = Lender.AAVE;
} else if (max == dapr) {
newProvider = Lender.DYDX;
}
return newProvider;
}
function GETAAVE657() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave).GETLENDINGPOOL795();
}
function GETAAVECORE248() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave).GETLENDINGPOOLCORE176();
}
function APPROVETOKEN94() public { //inject NONSTANDARD NAMING
IERC20(token).SAFEAPPROVE585(compound, uint(-1));
IERC20(token).SAFEAPPROVE585(dydx, uint(-1));
IERC20(token).SAFEAPPROVE585(GETAAVECORE248(), uint(-1));
IERC20(token).SAFEAPPROVE585(fulcrum, uint(-1));
}
function BALANCE782() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(address(this));
}
function BALANCEDYDXAVAILABLE330() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(dydx);
}
function BALANCEDYDX86() public view returns (uint256) { //inject NONSTANDARD NAMING
Wei memory bal = DyDx(dydx).GETACCOUNTWEI173(Info(address(this), 0), dToken);
return bal.value;
}
function BALANCECOMPOUND355() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(compound).BALANCEOF269(address(this));
}
function BALANCECOMPOUNDINTOKEN294() public view returns (uint256) { //inject NONSTANDARD NAMING
// Mantisa 1e18 to decimals
uint256 b = BALANCECOMPOUND355();
if (b > 0) {
b = b.MUL613(Compound(compound).EXCHANGERATESTORED297()).DIV312(1e18);
}
return b;
}
function BALANCEFULCRUMAVAILABLE395() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(chai).BALANCEOF269(fulcrum);
}
function BALANCEFULCRUMINTOKEN503() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 b = BALANCEFULCRUM271();
if (b > 0) {
b = Fulcrum(fulcrum).ASSETBALANCEOF748(address(this));
}
return b;
}
function BALANCEFULCRUM271() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(fulcrum).BALANCEOF269(address(this));
}
function BALANCEAAVEAVAILABLE892() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(aavePool);
}
function BALANCEAAVE873() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(aaveToken).BALANCEOF269(address(this));
}
function REBALANCE90() public { //inject NONSTANDARD NAMING
Lender newProvider = RECOMMEND876();
if (newProvider != provider) {
_WITHDRAWALL499();
}
if (BALANCE782() > 0) {
if (newProvider == Lender.DYDX) {
_SUPPLYDYDX870(BALANCE782());
} else if (newProvider == Lender.FULCRUM) {
_SUPPLYFULCRUM37(BALANCE782());
} else if (newProvider == Lender.COMPOUND) {
_SUPPLYCOMPOUND942(BALANCE782());
} else if (newProvider == Lender.AAVE) {
_SUPPLYAAVE258(BALANCE782());
}
}
provider = newProvider;
}
function _WITHDRAWALL499() internal { //inject NONSTANDARD NAMING
uint256 amount = BALANCECOMPOUND355();
if (amount > 0) {
_WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1));
}
amount = BALANCEDYDX86();
if (amount > 0) {
if (amount > BALANCEDYDXAVAILABLE330()) {
amount = BALANCEDYDXAVAILABLE330();
}
_WITHDRAWDYDX942(amount);
}
amount = BALANCEFULCRUM271();
if (amount > 0) {
if (amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) {
amount = BALANCEFULCRUMAVAILABLE395().SUB46(1);
}
_WITHDRAWSOMEFULCRUM209(amount);
}
amount = BALANCEAAVE873();
if (amount > 0) {
if (amount > BALANCEAAVEAVAILABLE892()) {
amount = BALANCEAAVEAVAILABLE892();
}
_WITHDRAWAAVE427(amount);
}
}
function _WITHDRAWSOMECOMPOUND259(uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 b = BALANCECOMPOUND355();
uint256 bT = BALANCECOMPOUNDINTOKEN294();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1);
_WITHDRAWCOMPOUND330(amount);
}
function _WITHDRAWSOMEFULCRUM209(uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 b = BALANCEFULCRUM271();
uint256 bT = BALANCEFULCRUMINTOKEN503();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1);
_WITHDRAWFULCRUM371(amount);
}
function _WITHDRAWSOME967(uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
uint256 origAmount = _amount;
uint256 amount = BALANCECOMPOUND355();
if (amount > 0) {
if (_amount > BALANCECOMPOUNDINTOKEN294().SUB46(1)) {
_WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1));
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWSOMECOMPOUND259(_amount);
return true;
}
}
amount = BALANCEDYDX86();
if (amount > 0) {
if (_amount > BALANCEDYDXAVAILABLE330()) {
_WITHDRAWDYDX942(BALANCEDYDXAVAILABLE330());
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWDYDX942(_amount);
return true;
}
}
amount = BALANCEFULCRUM271();
if (amount > 0) {
if (_amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) {
amount = BALANCEFULCRUMAVAILABLE395().SUB46(1);
_WITHDRAWSOMEFULCRUM209(BALANCEFULCRUMAVAILABLE395().SUB46(1));
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWSOMEFULCRUM209(amount);
return true;
}
}
amount = BALANCEAAVE873();
if (amount > 0) {
if (_amount > BALANCEAAVEAVAILABLE892()) {
_WITHDRAWAAVE427(BALANCEAAVEAVAILABLE892());
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWAAVE427(_amount);
return true;
}
}
return true;
}
function _SUPPLYDYDX870(uint256 amount) internal { //inject NONSTANDARD NAMING
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).OPERATE410(infos, args);
}
function _SUPPLYAAVE258(uint amount) internal { //inject NONSTANDARD NAMING
Aave(GETAAVE657()).DEPOSIT261(token, amount, 0);
}
function _SUPPLYFULCRUM37(uint amount) internal { //inject NONSTANDARD NAMING
require(Fulcrum(fulcrum).MINT570(address(this), amount) > 0, "FULCRUM: supply failed");
}
function _SUPPLYCOMPOUND942(uint amount) internal { //inject NONSTANDARD NAMING
require(Compound(compound).MINT570(amount) == 0, "COMPOUND: supply failed");
}
function _WITHDRAWAAVE427(uint amount) internal { //inject NONSTANDARD NAMING
AToken(aaveToken).REDEEM919(amount);
}
function _WITHDRAWFULCRUM371(uint amount) internal { //inject NONSTANDARD NAMING
require(Fulcrum(fulcrum).BURN957(address(this), amount) > 0, "FULCRUM: withdraw failed");
}
function _WITHDRAWCOMPOUND330(uint amount) internal { //inject NONSTANDARD NAMING
require(Compound(compound).REDEEM919(amount) == 0, "COMPOUND: withdraw failed");
}
function _WITHDRAWDYDX942(uint256 amount) internal { //inject NONSTANDARD NAMING
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).OPERATE410(infos, args);
}
function CALCPOOLVALUEINTOKEN983() public view returns (uint) { //inject NONSTANDARD NAMING
return BALANCECOMPOUNDINTOKEN294()
.ADD992(BALANCEFULCRUMINTOKEN503())
.ADD992(BALANCEDYDX86())
.ADD992(BALANCEAAVE873())
.ADD992(BALANCE782());
}
function GETPRICEPERFULLSHARE370() public view returns (uint) { //inject NONSTANDARD NAMING
uint _pool = CALCPOOLVALUEINTOKEN983();
return _pool.MUL613(1e18).DIV312(_totalSupply);
}
} | inject NONSTANDARD NAMING | function MINT570 ( uint256 mintAmount ) external returns ( uint256 ); | 977,143 |
pragma solidity ^0.4.0;
contract Marketplace {
bool completed;
uint256 priceTag;
address sellerAddress;
address ownerAddress;
event Transfer(address _address, uint256 _sent);
event Refund(address _address, uint256 _overpaidAmt);
event Status(bool _completed, uint256 _remainingAmt);
function Marketplace(address addr, uint256 price) public {
// buyer initiate contract to buy from seller.
require(price > 0);
completed = false;
ownerAddress = msg.sender;
priceTag = price;
sellerAddress = addr;
}
modifier isValidAddress(address addr) {
require(msg.sender==addr);
_;
}
function transfer() public payable {
// transfer fund to smart contract
require(msg.value > 0);
require(!completed);
Transfer(msg.sender, msg.value);
checkContractStatus();
}
function checkContractStatus() private {
// check if contract is completed
uint256 remainingAmt = priceTag - this.balance;
if (this.balance >= priceTag) {
completed = true;
remainingAmt = 0;
checkIfOverpaid();
}
Status(completed, remainingAmt);
}
function getBalance() public constant returns (uint256) {
return this.balance;
}
function checkIfOverpaid() private {
// if contract target is already fulfilled, refund all overpaid fund.
if (this.balance > priceTag) {
uint256 overpaidAmt = this.balance - priceTag;
msg.sender.transfer(overpaidAmt);
Refund(msg.sender, overpaidAmt);
}
}
function receivedItem() public isValidAddress(ownerAddress) {
// buyer received item, and close the deal.
require(completed);
sellerAddress.transfer(priceTag);
termination(ownerAddress);
}
function cancelOrder() public isValidAddress(sellerAddress) {
// seller cancel order, and refund to buyer.
// refund to buyer
termination(ownerAddress);
}
function termination(address addr) private {
selfdestruct(addr);
}
}
| buyer initiate contract to buy from seller. | function Marketplace(address addr, uint256 price) public {
require(price > 0);
completed = false;
ownerAddress = msg.sender;
priceTag = price;
sellerAddress = addr;
}
| 6,444,075 |
./partial_match/1/0x7119e8fe4a050CC267d5830F99adb309430F8a85/sources/Mogladys.sol | See {IERC721Enumerable-tokenByIndex}./ | function tokenByIndex(
uint256 index
) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
| 3,717,335 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
// File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol
/**
* @title Block Relay Interface
* @notice Interface of a Block Relay to a Witnet network
* It defines how to interact with the Block Relay in order to support:
* - Retrieve last beacon information
* - Verify proof of inclusions (PoIs) of data request and tally transactions
* @author Witnet Foundation
*/
interface BlockRelayInterface {
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory);
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view returns(uint256);
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view returns(uint256);
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies the validity of a tally PoI against the Tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid tally PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies if the block relay can be upgraded
/// @return true if contract is upgradable
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol
/**
* @title Block relay contract
* @notice Contract to store/read block headers from the Witnet network
* @author Witnet Foundation
*/
contract CentralizedBlockRelay is BlockRelayInterface {
struct MerkleRoots {
// hash of the merkle root of the DRs in Witnet
uint256 drHashMerkleRoot;
// hash of the merkle root of the tallies in Witnet
uint256 tallyHashMerkleRoot;
}
struct Beacon {
// hash of the last block
uint256 blockHash;
// epoch of the last block
uint256 epoch;
}
// Address of the block pusher
address public witnet;
// Last block reported
Beacon public lastBlock;
mapping (uint256 => MerkleRoots) public blocks;
// Event emitted when a new block is posted to the contract
event NewBlock(address indexed _from, uint256 _id);
// Only the owner should be able to push blocks
modifier isOwner() {
require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts.
_; // Otherwise, it continues.
}
// Ensures block exists
modifier blockExists(uint256 _id){
require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block");
_;
}
// Ensures block does not exist
modifier blockDoesNotExist(uint256 _id){
require(blocks[_id].drHashMerkleRoot==0, "The block already existed");
_;
}
constructor() public{
// Only the contract deployer is able to push blocks
witnet = msg.sender;
}
/// @dev Read the beacon of the last block inserted
/// @return bytes to be signed by bridge nodes
function getLastBeacon()
external
view
override
returns(bytes memory)
{
return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch);
}
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view override returns(uint256) {
return lastBlock.epoch;
}
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view override returns(uint256) {
return lastBlock.blockHash;
}
/// @dev Verifies the validity of a PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot;
return(verifyPoi(
_poi,
drMerkleRoot,
_index,
_element));
}
/// @dev Verifies the validity of a PoI against the tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the element
/// @return true or false depending the validity
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot;
return(verifyPoi(
_poi,
tallyMerkleRoot,
_index,
_element));
}
/// @dev Verifies if the contract is upgradable
/// @return true if the contract upgradable
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Post new block into the block relay
/// @param _blockHash Hash of the block header
/// @param _epoch Witnet epoch to which the block belongs to
/// @param _drMerkleRoot Merkle root belonging to the data requests
/// @param _tallyMerkleRoot Merkle root belonging to the tallies
function postNewBlock(
uint256 _blockHash,
uint256 _epoch,
uint256 _drMerkleRoot,
uint256 _tallyMerkleRoot)
external
isOwner
blockDoesNotExist(_blockHash)
{
lastBlock.blockHash = _blockHash;
lastBlock.epoch = _epoch;
blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot;
blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot;
emit NewBlock(witnet, _blockHash);
}
/// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header
/// @return Requests-only merkle root hash in the block header.
function readDrMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].drHashMerkleRoot;
}
/// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header.
/// @return tallies-only merkle root hash in the block header.
function readTallyMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].tallyHashMerkleRoot;
}
/// @dev Verifies the validity of a PoI
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _root the merkle root
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyPoi(
uint256[] memory _poi,
uint256 _root,
uint256 _index,
uint256 _element)
private pure returns(bool)
{
uint256 tree = _element;
uint256 index = _index;
// We want to prove that the hash of the _poi and the _element is equal to _root
// For knowing if concatenate to the left or the right we check the parity of the the index
for (uint i = 0; i < _poi.length; i++) {
if (index%2 == 0) {
tree = uint256(sha256(abi.encodePacked(tree, _poi[i])));
} else {
tree = uint256(sha256(abi.encodePacked(_poi[i], tree)));
}
index = index >> 1;
}
return _root == tree;
}
}
// File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay
* @dev More information can be found here
* DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks
* @author Witnet Foundation
*/
contract BlockRelayProxy {
// Address of the current controller
address internal blockRelayAddress;
// Current interface to the controller
BlockRelayInterface internal blockRelayInstance;
struct ControllerInfo {
// last epoch seen by a controller
uint256 lastEpoch;
// address of the controller
address blockRelayController;
}
// array containing the information about controllers
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use");
_;
}
constructor(address _blockRelayAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress}));
blockRelayAddress = _blockRelayAddress;
blockRelayInstance = BlockRelayInterface(_blockRelayAddress);
}
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory) {
return blockRelayInstance.getLastBeacon();
}
/// @notice Returns the last Wtinet epoch known to the block relay instance.
/// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request.
function getLastEpoch() external view returns(uint256) {
return blockRelayInstance.getLastEpoch();
}
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyDrPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Verifies the validity of a tally PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyTallyPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Upgrades the block relay if the current one is upgradeable
/// @param _newAddress address of the new block relay to upgrade
function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) {
// Check if the controller is upgradeable
require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Get last epoch seen by the replaced controller
uint256 epoch = blockRelayInstance.getLastEpoch();
// Get the length of last epochs seen by the different controllers
uint256 n = controllers.length;
// If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0
// just update the already anotated epoch with the new address, ignoring the previously inserted controller
// Else, anotate the epoch from which the new controller should start receiving blocks
if (epoch < controllers[n-1].lastEpoch) {
controllers[n-1].blockRelayController = _newAddress;
} else {
controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress}));
}
// Update instance
blockRelayAddress = _newAddress;
blockRelayInstance = BlockRelayInterface(_newAddress);
}
/// @notice Gets the controller associated with the BR controller corresponding to the epoch provided
/// @param _epoch the epoch to work with
function getController(uint256 _epoch) public view returns(address _controller) {
// Get length of all last epochs seen by controllers
uint256 n = controllers.length;
// Go backwards until we find the controller having that blockhash
for (uint i = n; i > 0; i--) {
if (_epoch >= controllers[i-1].lastEpoch) {
return (controllers[i-1].blockRelayController);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// 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;
}
}
// File: elliptic-curve-solidity/contracts/EllipticCurve.sol
/**
* @title Elliptic Curve Library
* @dev Library providing arithmetic operations over elliptic curves.
* @author Witnet Foundation
*/
library EllipticCurve {
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 newR = _x;
uint256 t;
while (newR != 0) {
t = r / newR;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, newR) = (newR, r - t * newR );
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) {
require(_pp!=0, "Modulus is zero");
if (_base == 0)
return 0;
if (_exp == 0)
return 1;
uint256 r = 1;
uint256 bit = 2 ** 255;
assembly {
for { } gt(bit, 0) { }{
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp)
internal pure returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp)
internal pure returns (uint256)
{
require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix");
// x^3 + ax + b
uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp)
internal pure returns (bool)
{
if (0 == _x || _x == _pp || 0 == _y || _y == _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp)
internal pure returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1==_x2) {
(x, y, z) = jacDouble(
_x1,
_y1,
1,
_aa,
_pp);
} else {
(x, y, z) = jacAdd(
_x1,
_y1,
1,
_x2,
_y2,
1,
_pp);
}
// Get back to affine
return toAffine(
x,
y,
z,
_pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(
_x1,
_y1,
x,
y,
_aa,
_pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(
_k,
_x,
_y,
1,
_aa,
_pp);
// Get back to affine
return toAffine(
x1,
y1,
z1,
_pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if ((_x1==0)&&(_y1==0))
return (_x2, _y2, _z2);
if ((_x2==0)&&(_y2==0))
return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(zs[0] != zs[2], "Invalid data");
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return(qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _pp the modulus
/// @param _aa the a scalar in the curve equation
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if (_z == 0)
return (_x, _y, _z);
uint256[3] memory square;
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
square[0] = mulmod(_x, _x, _pp); //x1^2
square[1] = mulmod(_y, _y, _pp); //y1^2
square[2] = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp);
// m
uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp);
// qx
uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp);
// qz = 2*y1*z1
uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
uint256 remaining = _d;
uint256[3] memory point;
point[0] = _x;
point[1] = _y;
point[2] = _z;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
if (_d == 0) {
return (qx, qy, qz);
}
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(
qx,
qy,
qz,
point[0],
point[1],
point[2],
_pp);
}
remaining = remaining / 2;
(point[0], point[1], point[2]) = jacDouble(
point[0],
point[1],
point[2],
_aa,
_pp);
}
return (qx, qy, qz);
}
}
// File: vrf-solidity/contracts/VRF.sol
/**
* @title Verifiable Random Functions (VRF)
* @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function.
* @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979).
* It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve.
* @author Witnet Foundation
*/
library VRF {
/**
* Secp256k1 parameters
*/
// Generator coordinate `x` of the EC curve
uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
// Generator coordinate `y` of the EC curve
uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Constant `a` of EC equation
uint256 public constant AA = 0;
// Constant `b` of EC equation
uint256 public constant BB = 7;
// Prime number of the curve
uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Order of the curve
uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @dev Public key derivation from private key.
/// @param _d The scalar
/// @param _x The coordinate x
/// @param _y The coordinate y
/// @return (qx, qy) The derived point
function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) {
return EllipticCurve.ecMul(
_d,
_x,
_y,
AA,
PP
);
}
/// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`).
/// @param _yByte The parity byte following the ec point compressed format
/// @param _x The coordinate `x` of the point
/// @return The coordinate `y` of the point
function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) {
return EllipticCurve.deriveY(
_yByte,
_x,
AA,
BB,
PP);
}
/// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix
/// concatenated with the gamma point
/// @param _gammaX The x-coordinate of the gamma EC point
/// @param _gammaY The y-coordinate of the gamma EC point
/// @return The VRF hash ouput as shas256 digest
function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) {
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(0xFE),
// 0x01
uint8(0x03),
// Compressed Gamma Point
encodePoint(_gammaX, _gammaY));
return sha256(c);
}
/// @dev VRF verification by providing the public key, the message and the VRF proof.
/// This function computes several elliptic curve operations which may lead to extensive gas consumption.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return true, if VRF proof is valid
function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) {
// Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3: U = s*B - c*Y (where B is the generator)
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Step 4: V = s*H - c*Gamma
(uint256 vPointX, uint256 vPointY) = ecMulSubMul(
_proof[3],
hPoint[0],
hPoint[1],
_proof[2],
_proof[0],_proof[1]);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
uPointX,
uPointY,
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut.
/// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @param _uPoint The `u` EC point defined as `U = s*B - c*Y`
/// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma`
/// @return true, if VRF proof is valid
function fastVerify(
uint256[2] memory _publicKey,
uint256[4] memory _proof,
bytes memory _message,
uint256[2] memory _uPoint,
uint256[4] memory _vComponents)
internal pure returns (bool)
{
// Step 2: Hash to try and increment -> hashed value, a finite EC point in G
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3 & Step 4:
// U = s*B - c*Y (where B is the generator)
// V = s*H - c*Gamma
if (!ecMulSubMulVerify(
_proof[3],
_proof[2],
_publicKey[0],
_publicKey[1],
_uPoint[0],
_uPoint[1]) ||
!ecMulVerify(
_proof[3],
hPoint[0],
hPoint[1],
_vComponents[0],
_vComponents[1]) ||
!ecMulVerify(
_proof[2],
_proof[0],
_proof[1],
_vComponents[2],
_vComponents[3])
)
{
return false;
}
(uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub(
_vComponents[0],
_vComponents[1],
_vComponents[2],
_vComponents[3],
AA,
PP);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
_uPoint[0],
_uPoint[1],
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev Decode VRF proof from bytes
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) {
require(_proof.length == 81, "Malformed VRF proof");
uint8 gammaSign;
uint256 gammaX;
uint128 c;
uint256 s;
assembly {
gammaSign := mload(add(_proof, 1))
gammaX := mload(add(_proof, 33))
c := mload(add(_proof, 49))
s := mload(add(_proof, 81))
}
uint256 gammaY = deriveY(gammaSign, gammaX);
return [
gammaX,
gammaY,
c,
s];
}
/// @dev Decode EC point from bytes
/// @param _point The EC point as bytes
/// @return The point as `[point-x, point-y]`
function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) {
require(_point.length == 33, "Malformed compressed EC point");
uint8 sign;
uint256 x;
assembly {
sign := mload(add(_point, 1))
x := mload(add(_point, 33))
}
uint256 y = deriveY(sign, x);
return [x, y];
}
/// @dev Compute the parameters (EC points) required for the VRF fast verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`
function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message)
internal pure returns (uint256[2] memory, uint256[4] memory)
{
// Requirements for Step 3: U = s*B - c*Y (where B is the generator)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Requirements for Step 4: V = s*H - c*Gamma
(uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]);
(uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]);
return (
[uPointX, uPointY],
[
sHX,
sHY,
cGammaX,
cGammaY
]);
}
/// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 2 of VRF verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _message The message used for computing the VRF
/// @return The hash point in affine cooridnates
function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) {
// Step 1: public key to bytes
// Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(254),
// 0x01
uint8(1),
// Public Key
encodePoint(_publicKey[0], _publicKey[1]),
// Message
_message);
// Step 3: find a valid EC point
// Loop over counter ctr starting at 0x00 and do hash
for (uint8 ctr = 0; ctr < 256; ctr++) {
// Counter update
// c[cLength-1] = byte(ctr);
bytes32 sha = sha256(abi.encodePacked(c, ctr));
// Step 4: arbitraty string to point and check if it is on curve
uint hPointX = uint256(sha);
uint hPointY = deriveY(2, hPointX);
if (EllipticCurve.isOnCurve(
hPointX,
hPointY,
AA,
BB,
PP))
{
// Step 5 (omitted): calculate H (cofactor is 1 on secp256k1)
// If H is not "INVALID" and cofactor > 1, set H = cofactor * H
return (hPointX, hPointY);
}
}
revert("No valid point was found");
}
/// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 5 of VRF verification function.
/// @param _hPointX The coordinate `x` of point `H`
/// @param _hPointY The coordinate `y` of point `H`
/// @param _gammaX The coordinate `x` of the point `Gamma`
/// @param _gammaX The coordinate `y` of the point `Gamma`
/// @param _uPointX The coordinate `x` of point `U`
/// @param _uPointY The coordinate `y` of point `U`
/// @param _vPointX The coordinate `x` of point `V`
/// @param _vPointY The coordinate `y` of point `V`
/// @return The first half of the digest of the points using SHA256
function hashPoints(
uint256 _hPointX,
uint256 _hPointY,
uint256 _gammaX,
uint256 _gammaY,
uint256 _uPointX,
uint256 _uPointY,
uint256 _vPointX,
uint256 _vPointY)
internal pure returns (bytes16)
{
bytes memory c = abi.encodePacked(
// Ciphersuite 0xFE
uint8(254),
// Prefix 0x02
uint8(2),
// Points to Bytes
encodePoint(_hPointX, _hPointY),
encodePoint(_gammaX, _gammaY),
encodePoint(_uPointX, _uPointY),
encodePoint(_vPointX, _vPointY)
);
// Hash bytes and truncate
bytes32 sha = sha256(c);
bytes16 half1;
assembly {
let freemem_pointer := mload(0x40)
mstore(add(freemem_pointer,0x00), sha)
half1 := mload(add(freemem_pointer,0x00))
}
return half1;
}
/// @dev Encode an EC point to bytes
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The point coordinates as bytes
function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) {
uint8 prefix = uint8(2 + (_y % 2));
return abi.encodePacked(prefix, _x);
}
/// @dev Substracts two key derivation functionsas `s1*A - s2*B`.
/// @param _scalar1 The scalar `s1`
/// @param _a1 The `x` coordinate of point `A`
/// @param _a2 The `y` coordinate of point `A`
/// @param _scalar2 The scalar `s2`
/// @param _b1 The `x` coordinate of point `B`
/// @param _b2 The `y` coordinate of point `B`
/// @return The derived point in affine cooridnates
function ecMulSubMul(
uint256 _scalar1,
uint256 _a1,
uint256 _a2,
uint256 _scalar2,
uint256 _b1,
uint256 _b2)
internal pure returns (uint256, uint256)
{
(uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2);
(uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2);
(uint256 r1, uint256 r2) = EllipticCurve.ecSub(
m1,
m2,
n1,
n2,
AA,
PP);
return (r1, r2);
}
/// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _scalar The scalar of the point multiplication
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @param _qx The coordinate `x` of the multiplication result
/// @param _qy The coordinate `y` of the multiplication result
/// @return true, if first 20 bytes match
function ecMulVerify(
uint256 _scalar,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
address result = ecrecover(
0,
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(_scalar, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on SolCrypto library: https://github.com/HarryR/solcrypto
/// @param _scalar1 The scalar of the multiplication of `(gx,gy)`
/// @param _scalar2 The scalar of the multiplication of `(x,y)`
/// @param _x The coordinate `x` of the point to be mutiply by `scalar2`
/// @param _y The coordinate `y` of the point to be mutiply by `scalar2`
/// @param _qx The coordinate `x` of the equation result
/// @param _qy The coordinate `y` of the equation result
/// @return true, if first 20 bytes match
function ecMulSubMulVerify(
uint256 _scalar1,
uint256 _scalar2,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
uint256 scalar1 = (NN - _scalar1) % NN;
scalar1 = mulmod(scalar1, _x, NN);
uint256 scalar2 = (NN - _scalar2) % NN;
address result = ecrecover(
bytes32(scalar1),
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(scalar2, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest.
/// This function is used for performing a fast EC multiplication verification.
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The address of the EC point digest (keccak256)
function pointToAddress(uint256 _x, uint256 _y)
internal pure returns(address)
{
return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
}
// File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol
/**
* @title Active Bridge Set (ABS) library
* @notice This library counts the number of bridges that were active recently.
*/
library ActiveBridgeSetLib {
// Number of Ethereum blocks during which identities can be pushed into a single activity slot
uint8 public constant CLAIM_BLOCK_PERIOD = 8;
// Number of activity slots in the ABS
uint8 public constant ACTIVITY_LENGTH = 100;
struct ActiveBridgeSet {
// Mapping of activity slots with participating identities
mapping (uint16 => address[]) epochIdentities;
// Mapping of identities with their participation count
mapping (address => uint16) identityCount;
// Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`)
uint32 activeIdentities;
// Number of identities for the next activity slot (to be updated in the next activity slot)
uint32 nextActiveIdentities;
// Last used block number during an activity update
uint256 lastBlockNumber;
}
modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) {
require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block");
_;
}
/// @dev Updates activity in Witnet without requiring protocol participation.
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _blockNumber The block number up to which the activity should be updated.
function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Avoid gas cost if ABS is up to date
require(
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
), "The ABS was already up to date");
_abs.lastBlockNumber = _blockNumber;
}
/// @dev Pushes activity updates through protocol activities (implying insertion of identity).
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _address The address pushing the activity.
/// @param _blockNumber The block number up to which the activity should be updated.
function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
returns (bool success)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Update ABS and if it was already up to date, check if identities already counted
if (
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
))
{
_abs.lastBlockNumber = _blockNumber;
} else {
// Check if address was already counted as active identity in this current activity slot
uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length;
for (uint256 i; i < epochIdsLength; i++) {
if (_abs.epochIdentities[currentSlot][i] == _address) {
return false;
}
}
}
// Update current activity slot with identity:
// 1. Add currentSlot to `epochIdentities` with address
// 2. If count = 0, increment by 1 `nextActiveIdentities`
// 3. Increment by 1 the count of the identity
_abs.epochIdentities[currentSlot].push(_address);
if (_abs.identityCount[_address] == 0) {
_abs.nextActiveIdentities++;
}
_abs.identityCount[_address]++;
return true;
}
/// @dev Checks if an address is a member of the ABS.
/// @param _abs The Active Bridge Set structure from the Witnet Requests Board.
/// @param _address The address to check.
/// @return true if address is member of ABS.
function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) {
return _abs.identityCount[_address] > 0;
}
/// @dev Gets the slots of the last block seen by the ABS provided and the block number provided.
/// @param _abs The Active Bridge Set structure containing the last block.
/// @param _blockNumber The block number from which to get the current slot.
/// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference > CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH.
function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) {
// Get current activity slot number
uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Get last actitivy slot number
uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Check if there was an activity slot overflow
// `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently
bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH);
return (currentSlot, lastSlot, overflow);
}
/// @dev Updates the provided ABS according to the slots provided.
/// @param _abs The Active Bridge Set to be updated.
/// @param _currentSlot The current slot.
/// @param _lastSlot The last slot seen by the ABS.
/// @param _overflow Whether the current slot has overflown the last slot.
/// @return True if update occurred.
function updateABS(
ActiveBridgeSet storage _abs,
uint16 _currentSlot,
uint16 _lastSlot,
bool _overflow)
private
returns (bool)
{
// If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS
if (_overflow) {
flushABS(_abs, _lastSlot, _lastSlot);
// If ABS are not up to date => fill previous activity slots with empty activities
} else if (_currentSlot != _lastSlot) {
flushABS(_abs, _currentSlot, _lastSlot);
} else {
return false;
}
return true;
}
/// @dev Flushes the provided ABS record between lastSlot and currentSlot.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _currentSlot The current slot.
function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private {
// For each slot elapsed, remove identities and update `nextActiveIdentities` count
for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) {
flushSlot(_abs, slot);
}
// Update current activity slot
flushSlot(_abs, _currentSlot);
_abs.activeIdentities = _abs.nextActiveIdentities;
}
/// @dev Flushes a slot of the provided ABS.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _slot The slot to be flushed.
function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private {
// For a given slot, go through all identities to flush them
uint256 epochIdsLength = _abs.epochIdentities[_slot].length;
for (uint256 id = 0; id < epochIdsLength; id++) {
flushIdentity(_abs, _abs.epochIdentities[_slot][id]);
}
delete _abs.epochIdentities[_slot];
}
/// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _address The address to be flushed.
function flushIdentity(ActiveBridgeSet storage _abs, address _address) private {
require(absMembership(_abs, _address), "The identity address is already out of the ARS");
// Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count
_abs.identityCount[_address]--;
if (_abs.identityCount[_address] == 0) {
delete _abs.identityCount[_address];
_abs.nextActiveIdentities--;
}
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol
/**
* @title Witnet Requests Board Interface
* @notice Interface of a Witnet Request Board (WRB)
* It defines how to interact with the WRB in order to support:
* - Post and upgrade a data request
* - Read the result of a dr
* @author Witnet Foundation
*/
interface WitnetRequestsBoardInterface {
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256);
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable;
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR
function readDrHash (uint256 _id) external view returns(uint256);
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult (uint256 _id) external view returns(bytes memory);
/// @notice Verifies if the block relay can be upgraded.
/// @return true if contract is upgradable.
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol
/**
* @title Witnet Requests Board
* @notice Contract to bridge requests to Witnet.
* @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.
* The result of the requests will be posted back to this contract by the bridge nodes too.
* @author Witnet Foundation
*/
contract WitnetRequestsBoard is WitnetRequestsBoardInterface {
using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet;
// Expiration period after which a Witnet Request can be claimed again
uint256 public constant CLAIM_EXPIRATION = 13;
struct DataRequest {
bytes dr;
uint256 inclusionReward;
uint256 tallyReward;
bytes result;
// Block number at which the DR was claimed for the last time
uint256 blockNumber;
uint256 drHash;
address payable pkhClaim;
}
// Owner of the Witnet Request Board
address public witnet;
// Block Relay proxy prividing verification functions
BlockRelayProxy public blockRelay;
// Witnet Requests within the board
DataRequest[] public requests;
// Set of recently active bridges
ActiveBridgeSetLib.ActiveBridgeSet public abs;
// Replication factor for Active Bridge Set identities
uint8 public repFactor;
// Event emitted when a new DR is posted
event PostedRequest(address indexed _from, uint256 _id);
// Event emitted when a DR inclusion proof is posted
event IncludedRequest(address indexed _from, uint256 _id);
// Event emitted when a result proof is posted
event PostedResult(address indexed _from, uint256 _id);
// Ensures the reward is not greater than the value
modifier payingEnough(uint256 _value, uint256 _tally) {
require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward");
_;
}
// Ensures the poe is valid
modifier poeValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) {
require(
verifyPoe(
_poe,
_publicKey,
_uPoint,
_vPointHelpers),
"Not a valid PoE");
_;
}
// Ensures signature (sign(msg.sender)) is valid
modifier validSignature(
uint256[2] memory _publicKey,
bytes memory addrSignature) {
require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature");
_;
}
// Ensures the DR inclusion proof has not been reported yet
modifier drNotIncluded(uint256 _id) {
require(requests[_id].drHash == 0, "DR already included");
_;
}
// Ensures the DR inclusion has been already reported
modifier drIncluded(uint256 _id) {
require(requests[_id].drHash != 0, "DR not yet included");
_;
}
// Ensures the result has not been reported yet
modifier resultNotIncluded(uint256 _id) {
require(requests[_id].result.length == 0, "Result already included");
_;
}
// Ensures the VRF is valid
modifier vrfValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) virtual {
require(
VRF.fastVerify(
_publicKey,
_poe,
getLastBeacon(),
_uPoint,
_vPointHelpers),
"Not a valid VRF");
_;
}
// Ensures the address belongs to the active bridge set
modifier absMember(address _address) {
require(abs.absMembership(_address), "Not a member of the ABS");
_;
}
/**
* @notice Include an address to specify the Witnet Block Relay and a replication factor.
* @param _blockRelayAddress BlockRelayProxy address.
* @param _repFactor replication factor.
*/
constructor(address _blockRelayAddress, uint8 _repFactor) public {
blockRelay = BlockRelayProxy(_blockRelayAddress);
witnet = msg.sender;
// Insert an empty request so as to initialize the requests array with length > 0
DataRequest memory request;
requests.push(request);
repFactor = _repFactor;
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _serialized, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
override
returns(uint256)
{
// The initial length of the `requests` array will become the ID of the request for everything related to the WRB
uint256 id = requests.length;
// Create a new `DataRequest` object and initialize all the non-default fields
DataRequest memory request;
request.dr = _serialized;
request.inclusionReward = SafeMath.sub(msg.value, _tallyReward);
request.tallyReward = _tallyReward;
// Push the new request into the contract state
requests.push(request);
// Let observers know that a new request has been posted
emit PostedRequest(msg.sender, id);
return id;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
resultNotIncluded(_id)
override
{
if (requests[_id].drHash != 0) {
require(
msg.value == _tallyReward,
"Txn value should equal result reward argument (request reward already paid)"
);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
} else {
requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
}
}
/// @dev Checks if the data requests from a list are claimable or not.
/// @param _ids The list of data request identifiers to be checked.
/// @return An array of booleans indicating if data requests are claimable or not.
function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) {
uint256 idsLength = _ids.length;
bool[] memory validIds = new bool[](idsLength);
for (uint i = 0; i < idsLength; i++) {
uint256 index = _ids[i];
validIds[i] = (dataRequestCanBeClaimed(requests[index])) &&
requests[index].drHash == 0 &&
index < requests.length &&
requests[index].result.length == 0;
}
return validIds;
}
/// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash).
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet.
/// @param _index The index in the merkle tree.
/// @param _blockHash The hash of the block in which the data request was inserted.
/// @param _epoch The epoch in which the blockHash was created.
function reportDataRequestInclusion(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch)
external
drNotIncluded(_id)
{
// Check the data request has been claimed
require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed");
uint256 drOutputHash = uint256(sha256(requests[_id].dr));
uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0])));
// Update the state upon which this function depends before the external call
requests[_id].drHash = drHash;
require(
blockRelay.verifyDrPoi(
_poi,
_blockHash,
_epoch,
_index,
drOutputHash), "Invalid PoI");
requests[_id].pkhClaim.transfer(requests[_id].inclusionReward);
// Push requests[_id].pkhClaim to abs
abs.pushActivity(requests[_id].pkhClaim, block.number);
emit IncludedRequest(msg.sender, _id);
}
/// @dev Reports the result of a data request in Witnet.
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block.
/// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block.
/// @param _blockHash The hash of the block in which the result (tally) was inserted.
/// @param _epoch The epoch in which the blockHash was created.
/// @param _result The result itself as bytes.
function reportResult(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch,
bytes calldata _result)
external
drIncluded(_id)
resultNotIncluded(_id)
absMember(msg.sender)
{
// Ensures the result byes do not have zero length
// This would not be a valid encoding with CBOR and could trigger a reentrancy attack
require(_result.length != 0, "Result has zero length");
// Update the state upon which this function depends before the external call
requests[_id].result = _result;
uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result)));
require(
blockRelay.verifyTallyPoi(
_poi,
_blockHash,
_epoch,
_index,
resHash), "Invalid PoI");
msg.sender.transfer(requests[_id].tallyReward);
emit PostedResult(msg.sender, _id);
}
/// @dev Retrieves the bytes of the serialization of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the data request as bytes.
function readDataRequest(uint256 _id) external view returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].dr;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult(uint256 _id) external view override returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].result;
}
/// @dev Retrieves hash of the data request transaction in Witnet.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DataRequest transaction in Witnet.
function readDrHash(uint256 _id) external view override returns(uint256) {
require(requests.length > _id, "Id not found");
return requests[_id].drHash;
}
/// @dev Returns the number of data requests in the WRB.
/// @return the number of data requests in the WRB.
function requestsCount() external view returns(uint256) {
return requests.length;
}
/// @notice Wrapper around the decodeProof from VRF library.
/// @dev Decode VRF proof from bytes.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) {
return VRF.decodeProof(_proof);
}
/// @notice Wrapper around the decodePoint from VRF library.
/// @dev Decode EC point from bytes.
/// @param _point The EC point as bytes.
/// @return The point as `[point-x, point-y]`.
function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) {
return VRF.decodePoint(_point);
}
/// @dev Wrapper around the computeFastVerifyParams from VRF library.
/// @dev Compute the parameters (EC points) required for the VRF fast verification function..
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @param _message The message (in bytes) used for computing the VRF.
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`.
function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message)
external pure returns (uint256[2] memory, uint256[4] memory)
{
return VRF.computeFastVerifyParams(_publicKey, _proof, _message);
}
/// @dev Updates the ABS activity with the block number provided.
/// @param _blockNumber update the ABS until this block number.
function updateAbsActivity(uint256 _blockNumber) external {
require (_blockNumber <= block.number, "The provided block number has not been reached");
abs.updateActivity(_blockNumber);
}
/// @dev Verifies if the contract is upgradable.
/// @return true if the contract upgradable.
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _ids Data request ids to be claimed.
/// @param _poe PoE claiming eligibility.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function claimDataRequests(
uint256[] memory _ids,
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers,
bytes memory addrSignature)
public
validSignature(_publicKey, addrSignature)
poeValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
for (uint i = 0; i < _ids.length; i++) {
require(
dataRequestCanBeClaimed(requests[_ids[i]]),
"One of the listed data requests was already claimed"
);
requests[_ids[i]].pkhClaim = msg.sender;
requests[_ids[i]].blockNumber = block.number;
}
return true;
}
/// @dev Read the beacon of the last block inserted.
/// @return bytes to be signed by the node as PoE.
function getLastBeacon() public view virtual returns(bytes memory) {
return blockRelay.getLastBeacon();
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _poe PoE claiming eligibility.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function verifyPoe(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers)
internal
view
vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1]));
// True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities
if (abs.activeIdentities < repFactor) {
return true;
}
// We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency
if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) {
return true;
}
return false;
}
/// @dev Verifies the validity of a signature.
/// @param _message message to be verified.
/// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`.
/// @param _addrSignature the signature to verify asas r||s||v.
/// @return true or false depending the validity.
function verifySig(
bytes memory _message,
uint256[2] memory _publicKey,
bytes memory _addrSignature)
internal
pure
returns(bool)
{
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_addrSignature, 0x20))
s := mload(add(_addrSignature, 0x40))
v := byte(0, mload(add(_addrSignature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return false;
}
if (v != 0 && v != 1) {
return false;
}
v = 28 - v;
bytes32 msgHash = sha256(_message);
address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]);
return ecrecover(
msgHash,
v,
r,
s) == hashedKey;
}
function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) {
return
(_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) &&
_request.drHash == 0 &&
_request.result.length == 0;
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay.
* @author Witnet Foundation
*/
contract WitnetRequestsBoardProxy {
// Address of the Witnet Request Board contract that is currently being used
address public witnetRequestsBoardAddress;
// Struct if the information of each controller
struct ControllerInfo {
// Address of the Controller
address controllerAddress;
// The lastId of the previous Controller
uint256 lastId;
}
// Last id of the WRB controller
uint256 internal currentLastId;
// Instance of the current WitnetRequestBoard
WitnetRequestsBoardInterface internal witnetRequestsBoardInstance;
// Array with the controllers that have been used in the Proxy
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use");
_;
}
/**
* @notice Include an address to specify the Witnet Request Board.
* @param _witnetRequestsBoardAddress WitnetRequestBoard address.
*/
constructor(address _witnetRequestsBoardAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0}));
witnetRequestsBoardAddress = _witnetRequestsBoardAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress);
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) {
uint256 n = controllers.length;
uint256 offset = controllers[n - 1].lastId;
// Update the currentLastId with the id in the controller plus the offSet
currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset;
return currentLastId;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable {
address wrbAddress;
uint256 wrbOffset;
(wrbAddress, wrbOffset) = getController(_id);
return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward);
}
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR.
function readDrHash (uint256 _id)
external
view
returns(uint256)
{
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offsetWrb;
(wrbAddress, offsetWrb) = getController(_id);
// Return the result of the DR readed in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithDrHash;
wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress);
uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb);
return drHash;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR.
function readResult(uint256 _id) external view returns(bytes memory) {
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offSetWrb;
(wrbAddress, offSetWrb) = getController(_id);
// Return the result of the DR in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithResult;
wrbWithResult = WitnetRequestsBoardInterface(wrbAddress);
return wrbWithResult.readResult(_id - offSetWrb);
}
/// @notice Upgrades the Witnet Requests Board if the current one is upgradeable.
/// @param _newAddress address of the new block relay to upgrade.
function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) {
// Require the WRB is upgradable
require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers
controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId}));
// Upgrade the WRB
witnetRequestsBoardAddress = _newAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress);
}
/// @notice Gets the controller from an Id.
/// @param _id id of a Data Request from which we get the controller.
function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
}
// File: witnet-ethereum-bridge/contracts/BufferLib.sol
/**
* @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface
* @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will
* start with the byte that goes right after the last one in the previous read.
* @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some
* theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded.
*/
library BufferLib {
struct Buffer {
bytes data;
uint32 cursor;
}
// Ensures we access an existing index in an array
modifier notOutOfBounds(uint32 index, uint256 length) {
require(index < length, "Tried to read from a consumed Buffer (must rewind it first)");
_;
}
/**
* @notice Read and consume a certain amount of bytes from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _length How many bytes to read and consume from the buffer.
* @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position.
*/
function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) {
// Make sure not to read out of the bounds of the original bytes
require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading");
// Create a new `bytes memory destination` value
bytes memory destination = new bytes(_length);
bytes memory source = _buffer.data;
uint32 offset = _buffer.cursor;
// Get raw pointers for source and destination
uint sourcePointer;
uint destinationPointer;
assembly {
sourcePointer := add(add(source, 32), offset)
destinationPointer := add(destination, 32)
}
// Copy `_length` bytes from source to destination
memcpy(destinationPointer, sourcePointer, uint(_length));
// Move the cursor forward by `_length` bytes
seek(_buffer, _length, true);
return destination;
}
/**
* @notice Read and consume the next byte from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The next byte in the buffer counting from the cursor position.
*/
function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) {
// Return the byte at the position marked by the cursor and advance the cursor all at once
return _buffer.data[_buffer.cursor++];
}
/**
* @notice Move the inner cursor of the buffer to a relative or absolute position.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _offset How many bytes to move the cursor forward.
* @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the
* buffer (`true`).
* @return The final position of the cursor (will equal `_offset` if `_relative` is `false`).
*/
// solium-disable-next-line security/no-assign-params
function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) {
// Deal with relative offsets
if (_relative) {
require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking");
_offset += _buffer.cursor;
}
// Make sure not to read out of the bounds of the original bytes
require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking");
_buffer.cursor = _offset;
return _buffer.cursor;
}
/**
* @notice Move the inner cursor a number of bytes forward.
* @dev This is a simple wrapper around the relative offset case of `seek()`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _relativeOffset How many bytes to move the cursor forward.
* @return The final position of the cursor.
*/
function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) {
return seek(_buffer, _relativeOffset, true);
}
/**
* @notice Move the inner cursor back to the first byte in the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function rewind(Buffer memory _buffer) internal pure {
_buffer.cursor = 0;
}
/**
* @notice Read and consume the next byte from the buffer as an `uint8`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint8` value of the next byte in the buffer counting from the cursor position.
*/
function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an `uint16`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position.
*/
function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint16 value;
assembly {
value := mload(add(add(bytesValue, 2), offset))
}
_buffer.cursor += 2;
return value;
}
/**
* @notice Read and consume the next 4 bytes from the buffer as an `uint32`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint32 value;
assembly {
value := mload(add(add(bytesValue, 4), offset))
}
_buffer.cursor += 4;
return value;
}
/**
* @notice Read and consume the next 8 bytes from the buffer as an `uint64`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position.
*/
function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint64 value;
assembly {
value := mload(add(add(bytesValue, 8), offset))
}
_buffer.cursor += 8;
return value;
}
/**
* @notice Read and consume the next 16 bytes from the buffer as an `uint128`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
*/
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
/**
* @notice Read and consume the next 32 bytes from the buffer as an `uint256`.
* @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an
* `int32`.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16`
* use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are
* expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readFloat16(Buffer memory _buffer) internal pure returns (int32) {
uint32 bytesValue = readUint16(_buffer);
// Get bit at position 0
uint32 sign = bytesValue & 0x8000;
// Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias
int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15;
// Get bits 6 to 15
int32 significand = int32(bytesValue & 0x03ff);
// Add 1024 to the fraction if the exponent is 0
if (exponent == 15) {
significand |= 0x400;
}
// Compute `2 ^ exponent · (1 + fraction / 1024)`
int32 result = 0;
if (exponent >= 0) {
result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10);
} else {
result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10);
}
// Make the result negative if the sign bit is not 0
if (sign != 0) {
result *= - 1;
}
return result;
}
/**
* @notice Copy bytes from one memory address into another.
* @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms
* of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE).
* @param _dest Address of the destination memory.
* @param _src Address to the source memory.
* @param _len How many bytes to copy.
*/
// solium-disable-next-line security/no-assign-params
function memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
}
// File: witnet-ethereum-bridge/contracts/CBOR.sol
/**
* @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation”
* @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize
* the gas cost of decoding them into a useful native type.
* @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js
* TODO: add support for Array (majorType = 4)
* TODO: add support for Map (majorType = 5)
* TODO: add support for Float32 (majorType = 7, additionalInformation = 26)
* TODO: add support for Float64 (majorType = 7, additionalInformation = 27)
*/
library CBOR {
using BufferLib for BufferLib.Buffer;
uint64 constant internal UINT64_MAX = ~uint64(0);
struct Value {
BufferLib.Buffer buffer;
uint8 initialByte;
uint8 majorType;
uint8 additionalInformation;
uint64 len;
uint64 tag;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `bytes` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `bytes` value.
*/
function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory bytesData;
// These checks look repetitive but the equivalent loop would be more expensive.
uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
}
}
return bytesData;
} else {
return _cborValue.buffer.read(uint32(_cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a `fixed16` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeFixed16(Value memory _cborValue) public pure returns(int32) {
require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7");
require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25");
return _cborValue.buffer.readFloat16();
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention.
* as explained in `decodeFixed16`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeFixed16(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeInt128(Value memory _cborValue) public pure returns(int128) {
if (_cborValue.majorType == 1) {
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
return int128(-1) - int128(length);
} else if (_cborValue.majorType == 0) {
// Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer
// a uniform API for positive and negative numbers
return int128(decodeUint64(_cborValue));
}
revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1");
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeInt128(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `string` value.
*/
function decodeString(Value memory _cborValue) public pure returns(string memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory textData;
bool done;
while (!done) {
uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType);
if (itemLength < UINT64_MAX) {
textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4));
} else {
done = true;
}
}
return string(textData);
} else {
return string(readText(_cborValue.buffer, _cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `string[]` value.
*/
function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) {
require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
string[] memory array = new string[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeString(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64` value.
*/
function decodeUint64(Value memory _cborValue) public pure returns(uint64) {
require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0");
return readLength(_cborValue.buffer, _cborValue.additionalInformation);
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64[]` value.
*/
function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) {
require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
uint64[] memory array = new uint64[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeUint64(item);
}
return array;
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) {
BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0);
return valueFromBuffer(buffer);
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _buffer A Buffer structure representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) {
require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value");
uint8 initialByte;
uint8 majorType = 255;
uint8 additionalInformation;
uint64 length;
uint64 tag = UINT64_MAX;
bool isTagged = true;
while (isTagged) {
// Extract basic CBOR properties from input bytes
initialByte = _buffer.readUint8();
majorType = initialByte >> 5;
additionalInformation = initialByte & 0x1f;
// Early CBOR tag parsing.
if (majorType == 6) {
tag = readLength(_buffer, additionalInformation);
} else {
isTagged = false;
}
}
require(majorType <= 7, "Invalid CBOR major type");
return CBOR.Value(
_buffer,
initialByte,
majorType,
additionalInformation,
length,
tag);
}
// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the
// value of the `additionalInformation` argument.
function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) {
if (additionalInformation < 24) {
return additionalInformation;
}
if (additionalInformation == 24) {
return _buffer.readUint8();
}
if (additionalInformation == 25) {
return _buffer.readUint16();
}
if (additionalInformation == 26) {
return _buffer.readUint32();
}
if (additionalInformation == 27) {
return _buffer.readUint64();
}
if (additionalInformation == 31) {
return UINT64_MAX;
}
revert("Invalid length encoding (non-existent additionalInformation value)");
}
// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming
// as many bytes as specified by the first byte.
function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) {
uint8 initialByte = _buffer.readUint8();
if (initialByte == 0xff) {
return UINT64_MAX;
}
uint64 length = readLength(_buffer, initialByte & 0x1f);
require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length");
return length;
}
// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness,
// but it can be easily casted into a string with `string(result)`.
// solium-disable-next-line security/no-assign-params
function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) {
bytes memory result;
for (uint64 index = 0; index < _length; index++) {
uint8 value = _buffer.readUint8();
if (value & 0x80 != 0) {
if (value < 0xe0) {
value = (value & 0x1f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 1;
} else if (value < 0xf0) {
value = (value & 0x0f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 2;
} else {
value = (value & 0x0f) << 18 |
(_buffer.readUint8() & 0x3f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 3;
}
}
result = abi.encodePacked(result, value);
}
return result;
}
}
// File: witnet-ethereum-bridge/contracts/Witnet.sol
/**
* @title A library for decoding Witnet request results
* @notice The library exposes functions to check the Witnet request success.
* and retrieve Witnet results from CBOR values into solidity types.
*/
library Witnet {
using CBOR for CBOR.Value;
/*
STRUCTS
*/
struct Result {
bool success;
CBOR.Value cborValue;
}
/*
ENUMS
*/
enum ErrorCodes {
// 0x00: Unknown error. Something went really bad!
Unknown,
// Script format errors
/// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
/// 0x02: The CBOR value decoded from a source script is not an Array.
SourceScriptNotArray,
/// 0x03: The Array value decoded form a source script is not a valid RADON script.
SourceScriptNotRADON,
/// Unallocated
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
ScriptFormat0x0E,
ScriptFormat0x0F,
// Complexity errors
/// 0x10: The request contains too many sources.
RequestTooManySources,
/// 0x11: The script contains too many calls.
ScriptTooManyCalls,
/// Unallocated
Complexity0x12,
Complexity0x13,
Complexity0x14,
Complexity0x15,
Complexity0x16,
Complexity0x17,
Complexity0x18,
Complexity0x19,
Complexity0x1A,
Complexity0x1B,
Complexity0x1C,
Complexity0x1D,
Complexity0x1E,
Complexity0x1F,
// Operator errors
/// 0x20: The operator does not exist.
UnsupportedOperator,
/// Unallocated
Operator0x21,
Operator0x22,
Operator0x23,
Operator0x24,
Operator0x25,
Operator0x26,
Operator0x27,
Operator0x28,
Operator0x29,
Operator0x2A,
Operator0x2B,
Operator0x2C,
Operator0x2D,
Operator0x2E,
Operator0x2F,
// Retrieval-specific errors
/// 0x30: At least one of the sources could not be retrieved, but returned HTTP error.
HTTP,
/// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
/// Unallocated
Retrieval0x32,
Retrieval0x33,
Retrieval0x34,
Retrieval0x35,
Retrieval0x36,
Retrieval0x37,
Retrieval0x38,
Retrieval0x39,
Retrieval0x3A,
Retrieval0x3B,
Retrieval0x3C,
Retrieval0x3D,
Retrieval0x3E,
Retrieval0x3F,
// Math errors
/// 0x40: Math operator caused an underflow.
Underflow,
/// 0x41: Math operator caused an overflow.
Overflow,
/// 0x42: Tried to divide by zero.
DivisionByZero,
Size
}
/*
Result impl's
*/
/**
* @notice Decode raw CBOR bytes into a Result instance.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `Result` instance.
*/
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) {
CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes);
return resultFromCborValue(cborValue);
}
/**
* @notice Decode a CBOR value into a Result instance.
* @param _cborValue An instance of `CBOR.Value`.
* @return A `Result` instance.
*/
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) {
// Witnet uses CBOR tag 39 to represent RADON error code identifiers.
// [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md
bool success = _cborValue.tag != 39;
return Result(success, _cborValue);
}
/**
* @notice Tell if a Result is successful.
* @param _result An instance of Result.
* @return `true` if successful, `false` if errored.
*/
function isOk(Result memory _result) public pure returns(bool) {
return _result.success;
}
/**
* @notice Tell if a Result is errored.
* @param _result An instance of Result.
* @return `true` if errored, `false` if successful.
*/
function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
/**
* @notice Decode a bytes value from a Result as a `bytes` value.
* @param _result An instance of Result.
* @return The `bytes` decoded from the Result.
*/
function asBytes(Result memory _result) public pure returns(bytes memory) {
require(_result.success, "Tried to read bytes value from errored Result");
return _result.cborValue.decodeBytes();
}
/**
* @notice Decode an error code from a Result as a member of `ErrorCodes`.
* @param _result An instance of `Result`.
* @return The `CBORValue.Error memory` decoded from the Result.
*/
function asErrorCode(Result memory _result) public pure returns(ErrorCodes) {
uint64[] memory error = asRawError(_result);
return supportedErrorOrElseUnknown(error[0]);
}
/**
* @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments.
* @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
* @param _result An instance of `Result`.
* @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message.
*/
function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) {
uint64[] memory error = asRawError(_result);
ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]);
bytes memory errorMessage;
if (errorCode == ErrorCodes.SourceScriptNotCBOR) {
errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value");
} else if (errorCode == ErrorCodes.SourceScriptNotArray) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls");
} else if (errorCode == ErrorCodes.SourceScriptNotRADON) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script");
} else if (errorCode == ErrorCodes.RequestTooManySources) {
errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")");
} else if (errorCode == ErrorCodes.ScriptTooManyCalls) {
errorMessage = abi.encodePacked(
"Script #",
utoa(error[2]),
" from the ",
stageName(error[1]),
" stage contained too many calls (",
utoa(error[3]),
")"
);
} else if (errorCode == ErrorCodes.UnsupportedOperator) {
errorMessage = abi.encodePacked(
"Operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage is not supported"
);
} else if (errorCode == ErrorCodes.HTTP) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved. Failed with HTTP error code: ",
utoa(error[2] / 100),
utoa(error[2] % 100 / 10),
utoa(error[2] % 10)
);
} else if (errorCode == ErrorCodes.RetrievalTimeout) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved because of a timeout."
);
} else if (errorCode == ErrorCodes.Underflow) {
errorMessage = abi.encodePacked(
"Underflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.Overflow) {
errorMessage = abi.encodePacked(
"Overflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.DivisionByZero) {
errorMessage = abi.encodePacked(
"Division by zero at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else {
errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")");
}
return (errorCode, string(errorMessage));
}
/**
* @notice Decode a raw error from a `Result` as a `uint64[]`.
* @param _result An instance of `Result`.
* @return The `uint64[]` raw error as decoded from the `Result`.
*/
function asRawError(Result memory _result) public pure returns(uint64[] memory) {
require(!_result.success, "Tried to read error code from successful Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asFixed16(Result memory _result) public pure returns(int32) {
require(_result.success, "Tried to read `fixed16` value from errored Result");
return _result.cborValue.decodeFixed16();
}
/**
* @notice Decode an array of fixed16 values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asFixed16Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `fixed16[]` value from errored Result");
return _result.cborValue.decodeFixed16Array();
}
/**
* @notice Decode a integer numeric value from a Result as an `int128` value.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
/**
* @notice Decode an array of integer numeric values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asInt128Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `int128[]` value from errored Result");
return _result.cborValue.decodeInt128Array();
}
/**
* @notice Decode a string value from a Result as a `string` value.
* @param _result An instance of Result.
* @return The `string` decoded from the Result.
*/
function asString(Result memory _result) public pure returns(string memory) {
require(_result.success, "Tried to read `string` value from errored Result");
return _result.cborValue.decodeString();
}
/**
* @notice Decode an array of string values from a Result as a `string[]` value.
* @param _result An instance of Result.
* @return The `string[]` decoded from the Result.
*/
function asStringArray(Result memory _result) public pure returns(string[] memory) {
require(_result.success, "Tried to read `string[]` value from errored Result");
return _result.cborValue.decodeStringArray();
}
/**
* @notice Decode a natural numeric value from a Result as a `uint64` value.
* @param _result An instance of Result.
* @return The `uint64` decoded from the Result.
*/
function asUint64(Result memory _result) public pure returns(uint64) {
require(_result.success, "Tried to read `uint64` value from errored Result");
return _result.cborValue.decodeUint64();
}
/**
* @notice Decode an array of natural numeric values from a Result as a `uint64[]` value.
* @param _result An instance of Result.
* @return The `uint64[]` decoded from the Result.
*/
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) {
require(_result.success, "Tried to read `uint64[]` value from errored Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Convert a stage index number into the name of the matching Witnet request stage.
* @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages.
* @return The name of the matching stage.
*/
function stageName(uint64 _stageIndex) public pure returns(string memory) {
if (_stageIndex == 0) {
return "retrieval";
} else if (_stageIndex == 1) {
return "aggregation";
} else if (_stageIndex == 2) {
return "tally";
} else {
return "unknown";
}
}
/**
* @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't
* exist.
* @param _discriminant The numeric identifier of an error.
* @return A member of `ErrorCodes`.
*/
function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) {
if (_discriminant < uint8(ErrorCodes.Size)) {
return ErrorCodes(_discriminant);
} else {
return ErrorCodes.Unknown;
}
}
/**
* @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its.
* three less significant decimal values.
* @param _u A `uint64` value.
* @return The `string` representing its decimal value.
*/
function utoa(uint64 _u) private pure returns(string memory) {
if (_u < 10) {
bytes memory b1 = new bytes(1);
b1[0] = byte(uint8(_u) + 48);
return string(b1);
} else if (_u < 100) {
bytes memory b2 = new bytes(2);
b2[0] = byte(uint8(_u / 10) + 48);
b2[1] = byte(uint8(_u % 10) + 48);
return string(b2);
} else {
bytes memory b3 = new bytes(3);
b3[0] = byte(uint8(_u / 100) + 48);
b3[1] = byte(uint8(_u % 100 / 10) + 48);
b3[2] = byte(uint8(_u % 10) + 48);
return string(b3);
}
}
/**
* @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values.
* @param _u A `uint64` value.
* @return The `string` representing its hexadecimal value.
*/
function utohex(uint64 _u) private pure returns(string memory) {
bytes memory b2 = new bytes(2);
uint8 d0 = uint8(_u / 16) + 48;
uint8 d1 = uint8(_u % 16) + 48;
if (d0 > 57)
d0 += 7;
if (d1 > 57)
d1 += 7;
b2[0] = byte(d0);
b2[1] = byte(d1);
return string(b2);
}
}
// File: witnet-ethereum-bridge/contracts/Request.sol
/**
* @title The serialized form of a Witnet data request
*/
contract Request {
bytes public bytecode;
uint256 public id;
/**
* @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized
* using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using
* the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests.
* The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a
* mismatch and a data request could be resolved with the result of another.
* @param _bytecode Witnet request in bytes.
*/
constructor(bytes memory _bytecode) public {
bytecode = _bytecode;
id = uint256(sha256(_bytecode));
}
}
// File: witnet-ethereum-bridge/contracts/UsingWitnet.sol
/**
* @title The UsingWitnet contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Witnet network.
*/
contract UsingWitnet {
using Witnet for Witnet.Result;
WitnetRequestsBoardProxy internal wrb;
/**
* @notice Include an address to specify the WitnetRequestsBoard.
* @param _wrb WitnetRequestsBoard address.
*/
constructor(address _wrb) public {
wrb = WitnetRequestsBoardProxy(_wrb);
}
// Provides a convenient way for client contracts extending this to block the execution of the main logic of the
// contract until a particular request has been successfully accepted into Witnet
modifier witnetRequestAccepted(uint256 _id) {
require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network");
_;
}
// Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value
modifier validRewards(uint256 _requestReward, uint256 _resultReward) {
require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows");
require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards");
_;
}
/**
* @notice Send a new request to the Witnet network
* @dev Call to `post_dr` function in the WitnetRequestsBoard contract
* @param _request An instance of the `Request` contract
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which posts back the request result
* @return Sequencial identifier for the request included in the WitnetRequestsBoard
*/
function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
returns (uint256)
{
return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward);
}
/**
* @notice Check if a request has been accepted into Witnet.
* @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third.
* parties) before this method returns `true`.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though.
*/
function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) {
// Find the request in the
uint256 drHash = wrb.readDrHash(_id);
// If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the
// request has been proven to the WRB.
return drHash != 0;
}
/**
* @notice Upgrade the rewards for a Data Request previously included.
* @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which post the Data Request result.
*/
function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
{
wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward);
}
/**
* @notice Read the result of a resolved request.
* @dev Call to `read_result` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that was posted to Witnet.
* @return The result of the request as an instance of `Result`.
*/
function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) {
return Witnet.resultFromCborBytes(wrb.readResult(_id));
}
}
// File: adomedianizer/contracts/IERC2362.sol
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface IERC2362
{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
// File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol
// The bytecode of the BitcoinPrice request that will be sent to Witnet
contract BitcoinPriceRequest is Request {
constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the BitcoinPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract BtcUsdPriceFeed is UsingWitnet, IERC2362 {
// The public Bitcoin price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is `keccak256("Price-BTC/USD-3")`
bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new BitcoinPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != BTCUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol
// The bytecode of the EthPrice request that will be sent to Witnet
contract EthPriceRequest is Request {
constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the ethPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract EthUsdPriceFeed is UsingWitnet, IERC2362 {
// The public eth price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")`
bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new EthPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != ETHUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol
// The bytecode of the GoldPrice request that will be sent to Witnet
contract GoldPriceRequest is Request {
constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the goldPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract GoldEurPriceFeed is UsingWitnet, IERC2362 {
// The public gold price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")`
bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new GoldPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != XAUEUR3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: contracts/Deployer.sol
// Import witnet-ethereum-block-relay-contracts
// Import the UsingWitnet library that enables interacting with Witnet
// Import price feeds
contract Deployer {
}
// File: contracts/Migrations.sol
contract Migrations {
address public owner;
uint public lastCompletedMigration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner)
_;
}
function setCompleted(uint _completed) public restricted {
lastCompletedMigration = _completed;
}
function upgrade(address _newAddress) public restricted {
Migrations upgraded = Migrations(_newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| Read and consume the next 32 bytes from the buffer as an `uint256`. return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. _buffer An instance of `BufferLib.Buffer`./ | function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
| 901,207 |
// SPDX-License-Identifier: UNLICENSED
// ANCHOR: all
pragma solidity 0.8.10;
// ANCHOR: import
import "forge-std/Test.sol";
// ANCHOR_END: import
contract ContractBTest is Test {
uint256 testNumber;
// ANCHOR: setUp
function setUp() public {
testNumber = 42;
}
// ANCHOR_END: setUp
// ANCHOR: testNumberIs42
function testNumberIs42() public {
assertEq(testNumber, 42);
}
// ANCHOR_END: testNumberIs42
// ANCHOR: testFailSubtract43
function testFailSubtract43() public {
testNumber -= 43;
}
// ANCHOR_END: testFailSubtract43
}
// ANCHOR_END: all
| ANCHOR: testFailSubtract43 | function testFailSubtract43() public {
testNumber -= 43;
}
| 13,043,061 |
./full_match/3/0x3f4b235e4e83D75D0938Fc83dafA4033412A6fD1/sources/TestSelf.sol | You can send ether and specify a custom gas amount | function testCallFoo(address payable _addr) public payable {
abi.encodeWithSignature("foo(string,uint256)", "call foo", 123)
);
emit Response(success, data);
}
| 8,128,454 |
/**
* Geostellar, Inc.
* All rights reserved.
* The Dividend contract is a bit what it sounds like: it allows payments to
* be made to a contract and for them to be withdrawn. The trick of it is that
* one can only withdraw the latest payment.
*/
pragma solidity ^0.4.13;
import 'zeppelin-solidity/contracts/token/StandardToken.sol';
import 'zeppelin-solidity/contracts/payment/PullPayment.sol';
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
contract Dividend is Ownable, StandardToken, PullPayment {
using SafeMath for uint256;
mapping(uint256 => uint256) public paidIn;
uint256 public currentPeriod;
mapping (address => mapping (uint256 => uint256)) periodWithdrawn;
mapping(uint256 => uint256) public excludeFromTotal; // To keep new tokens from diluting
//dividends in current period
event DividendPayment(address indexed recipient, uint256 weiPayment);
function Dividend () {
currentPeriod = 0;
}
/**
* @dev Charge a period's dividend
* @param _period The period of the balance submitted.
*/
function payDividend (uint256 _period) public payable onlyOwner {
paidIn[_period] = msg.value;
currentPeriod = _period;
}
/**
* @dev Show a period's dividend
* @param _period The period of the balance to show.
*/
function showDividend (uint256 _period) public constant returns (uint256) {
return paidIn[_period];
}
/**
* @dev Check how much a dividend payment for the period would be.
*/
function checkDividend () public constant returns(uint256) {
if (msg.sender == owner) {
return 0;
}
uint256 senderBalance = balances[msg.sender];
uint256 periodDividiend = paidIn[currentPeriod];
uint256 portion = periodDividiend.mul(senderBalance).div(totalSupply.sub(balances[owner]).sub(excludeFromTotal[currentPeriod]));
if (periodWithdrawn[msg.sender][currentPeriod] >= portion){
return 0;
}
uint256 withdrawn = portion.sub(periodWithdrawn[msg.sender][currentPeriod]);
return withdrawn;
}
/**
* @dev Withdraw the dividend.
*
* Note that after this call one still needs to withdrawPayments (from PullPayment)
*/
function withdrawDvidend () public {
require(msg.sender != owner);
uint256 withdrawn = checkDividend();
require(withdrawn > 0);
periodWithdrawn[msg.sender][currentPeriod] = periodWithdrawn[msg.sender][currentPeriod].add(withdrawn);
asyncSend(msg.sender, withdrawn);
DividendPayment(msg.sender, withdrawn);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*
* Note that this is an override of the version that is found in BasicToken. This
* version makes sure that one can't withdraw the last dividend from transferred tokens.
* As with an equity, one can collect the *next* payment, not the previous.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
if (msg.sender == owner) {
excludeFromTotal[currentPeriod] = excludeFromTotal[currentPeriod].add(_value);
}
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// The new code:
uint256 periodDividiend = paidIn[currentPeriod];
uint256 portion;
if (balances[owner] + excludeFromTotal[currentPeriod] >= totalSupply){
portion = 0;
} else {
portion = periodDividiend.mul(_value).div(totalSupply.sub(balances[owner]).sub(excludeFromTotal[currentPeriod]));
}
periodWithdrawn[_to][currentPeriod] = periodWithdrawn[_to][currentPeriod].add(portion);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*
* Again, this is an override of the transferFrom function (in this case
* in StandardToken) to ensure that the transferred tokens don't affect
* divided payments
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
if (_from == owner) {
excludeFromTotal[currentPeriod] = excludeFromTotal[currentPeriod].add(_value);
}
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
// New code
uint256 periodDividiend = paidIn[currentPeriod];
uint256 portion;
if (balances[owner] + excludeFromTotal[currentPeriod] >= totalSupply){
portion = 0;
} else {
portion = periodDividiend.mul(_value).div(totalSupply.sub(balances[owner]).sub(excludeFromTotal[currentPeriod]));
}
periodWithdrawn[_to][currentPeriod] = periodWithdrawn[_to][currentPeriod].add(portion);
Transfer(_from, _to, _value);
return true;
}
}
| Check how much a dividend payment for the period would be./ | function checkDividend () public constant returns(uint256) {
if (msg.sender == owner) {
return 0;
}
uint256 senderBalance = balances[msg.sender];
uint256 periodDividiend = paidIn[currentPeriod];
uint256 portion = periodDividiend.mul(senderBalance).div(totalSupply.sub(balances[owner]).sub(excludeFromTotal[currentPeriod]));
if (periodWithdrawn[msg.sender][currentPeriod] >= portion){
return 0;
}
uint256 withdrawn = portion.sub(periodWithdrawn[msg.sender][currentPeriod]);
return withdrawn;
}
| 941,818 |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationDecoder.sol | Converts a function taking a calldata pointer and returning a memory pointer into a function taking that calldata pointer and returning an OrderParameters type. inFn The input function, taking an arbitrary calldata pointer and returning an arbitrary memory pointer. return outFn The output function, taking an arbitrary calldata pointer and returning an OrderParameters type./ | function _toOrderParametersReturnType(
function(CalldataPointer) internal pure returns (MemoryPointer) inFn
)
internal
pure
returns (
function(CalldataPointer)
internal
pure
returns (OrderParameters memory) outFn
)
{
assembly {
outFn := inFn
}
}
| 4,301,700 |
./full_match/1/0x5de58BF4ef40e923797aFF1767F8ed4143e6c032/sources/contracts/utils/WadRayMath.sol | Scales a value in RAY down to a value in WAD a RAY value return a, scaled down to a value in WAD (rounded up to the nearest WAD)/ | function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 result = a / WAD_RAY_RATIO;
if (a % WAD_RAY_RATIO >= HALF_RATIO) {
result += 1;
}
return result;
}
| 16,410,621 |
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File contracts/MVM/iMVM_DiscountOracle.sol
// MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/libraries/resolver/Lib_AddressManager.sol
// MIT
pragma solidity ^0.8.9;
/* External Imports */
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address) external onlyOwner {
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// File contracts/libraries/resolver/Lib_AddressResolver.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// File contracts/libraries/rlp/Lib_RLPReader.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })
);
out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset });
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in) internal pure returns (string memory) {
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, "Invalid RLP boolean value.");
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, "RLP item cannot be null.");
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, "Invalid RLP short list.");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, "Invalid RLP long list length.");
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// File contracts/libraries/rlp/Lib_RLPWriter.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// File contracts/libraries/utils/Lib_BytesUtils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// File contracts/libraries/utils/Lib_Bytes32Utils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// File contracts/libraries/codec/Lib_OVMCodec.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// File contracts/libraries/utils/Lib_MerkleTree.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
) internal pure returns (bool) {
require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
} else {
computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(uint256 _in) private pure returns (uint256) {
require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint256(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// File contracts/L1/rollup/IChainStorageContainer.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Set an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _index position.
* @param _object A 32 byte value to insert into the container.
*/
function setByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _chainId identity for the l2 chain.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @param _chainId identity for the l2 chain.
* @return Container global metadata field.
*/
function getGlobalMetadataByChainId(
uint256 _chainId
)
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @param _chainId identity for the l2 chain.
* @return Number of objects in the container.
*/
function lengthByChainId(
uint256 _chainId
)
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _chainId identity for the l2 chain.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function getByChainId(
uint256 _chainId,
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// File contracts/L1/rollup/IStateCommitmentChain.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
/**
* @title IStateCommitmentChain
*/
interface IStateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
function batches() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
) external view returns (bool _verified);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
external
view
returns (
bool _inside
);
/********************
* chain id added func *
********************/
/**
* Retrieves the total number of elements submitted.
* @param _chainId identity for the l2 chain.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @param _chainId identity for the l2 chain.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @param _chainId identity for the l2 chain.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestampByChainId(uint256 _chainId)
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _chainId identity for the l2 chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatchByChainId(
uint256 _chainId,
bytes32[] calldata _batch,
uint256 _shouldStartAtElement,
string calldata proposer
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatchByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _chainId identity for the l2 chain.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitmentByChainId(
uint256 _chainId,
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindowByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// File contracts/MVM/MVM_Verifier.sol
// MIT
pragma solidity ^0.8.9;
/* Contract Imports */
/* External Imports */
contract MVM_Verifier is Lib_AddressResolver{
// second slot
address public metis;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
//challenge info
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
// only one active challenge for each chain chainid=>cIndex
mapping (uint256 => uint256) public chain_under_challenge;
// white list
mapping (address => bool) public whitelist;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
uint FAIL_THRESHOLD = 2; // 1 time grace
uint ABSENCE_THRESHOLD = 4; // 2 times grace
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
// add stake as a verifier
function verifierStake(uint256 stake) public onlyWhitelisted{
require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
// start a new challenge
// @param chainID chainid
// @param header chainbatch header
// @param proposedHash encrypted hash of the correct state
// @param keyhash hash of the decryption key
//
// @dev why do we ask for key and keyhash? because we want verifiers compute the state instead
// of just copying from other verifiers.
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
// while the root is encrypted, the timestamp is available in the extradata field of the header
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
// house keeping
challenge_hashes[cIndex][msg.sender] = proposedHash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++; // the challenger
// this will prevent stake change
activeChallenges++;
chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
// phase 1 of the verify, provide an encrypted hash and the hash of the decryption key
// @param cIndex index of the challenge
// @param hash encrypted hash of the correct state (for the index referred in the challenge)
// @param keyhash hash of the decryption key
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
// phase 2 of the verify, provide the actual key to decrypt the hash
// @param cIndex index of the challenge
// @param key the decryption key
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
//verify whether the key matches the keyhash initially provided.
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
if (msg.sender == challenges[cIndex].challenger) {
//decode the root in the header too
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
// not ready to finalize. do nothing
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
// not qualified as a verifier
continue;
}
//record the agreement
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
//agree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
//absent
absence_strikes[verifiers[i]] += 2;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
} else {
//disagree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
// wrong header, penalize the challenger
reward += penalize(challenge.challenger);
// reward the disagrees. but no penalty on agrees because the input
// is garbage.
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
// the absent verifiers get a absense strike. no other penalties. already done
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
// no consensus, challenge failed.
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else {
// reached agreement. delete the batch root and slash the sequencer if the header is still valid
if(stateChain.insideFraudProofWindow(challenge.header)) {
// this header needs to be within the window
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
// temporary for the p1 of the decentralization roadmap
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
} else {
//not in the window anymore. let it pass... no penalty
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
}
}
} else {
//wasteful challenge, add consensus_strikes to the challenger
consensus_strikes[challenge.challenger] += 2;
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
// helper
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
// set the length of the time windows for each verification phase
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
// add the verifier to the whitelist
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
// allow everyone to be the verifier
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
//helper fucntion to encrypt data
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
// helper fucntion to decrypt the data
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
} else {
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
// calculate the rewards
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
} else {
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
// slash the verifier stake
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
} | Converts bytes to a reference to memory position and length. _in Input bytes to convert. return Output memory reference./ | function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
}
| 366,068 |
// Sources flattened with hardhat v2.1.1 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 contracts/interfaces/IDetailedERC20.sol
pragma solidity ^0.6.12;
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// File contracts/interfaces/IMintableERC20.sol
pragma solidity ^0.6.12;
interface IMintableERC20 is IDetailedERC20{
function mint(address _recipient, uint256 _amount) external;
function burnFrom(address account, uint256 amount) external;
function lowerHasMinted(uint256 amount)external;
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.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/interfaces/IRewardVesting.sol
pragma solidity ^0.6.12;
interface IRewardVesting {
function addEarning(address user, uint256 amount) external;
function userBalances(address user) external view returns (uint256 bal);
}
// File contracts/interfaces/IVotingEscrow.sol
pragma solidity ^0.6.12;
interface IVotingEscrow {
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// File hardhat/[email protected]
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File contracts/StakingPoolsV4.sol
contract StakingPoolsV4 is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 workingAmount; // actual amount * ve boost * lockup bonus
uint256 rewardDebt; // Reward debt.
uint256 power;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool.
uint256 lastRewardBlock; // Last block number that Wasabi distribution occurs.
uint256 accRewardPerShare; // Accumulated Wasabi per share, times 1e18. See below.
uint256 workingSupply; // Total supply of working amount
uint256 totalDeposited;
bool needVesting;
uint256 earlyWithdrawFee; // divided by 10000
uint256 withdrawLock; // in second
bool veBoostEnabled;
mapping (address => UserInfo) userInfo;
}
/// @dev A mapping of all of the user deposit time mapped first by pool and then by address.
mapping(address => mapping(uint256 => uint256)) private _depositedAt;
/// @dev A mapping of userIsKnown mapped first by pool and then by address.
mapping(address => mapping(uint256 => bool)) public userIsKnown;
/// @dev A mapping of userAddress mapped first by pool and then by nextUser.
mapping(uint256 => mapping(uint256 => address)) public userList;
/// @dev index record next user index mapped by pool
mapping(uint256 => uint256) public nextUser;
// The Wasabi TOKEN!
IMintableERC20 public reward;
/// @dev The address of reward vesting.
IRewardVesting public rewardVesting;
IVotingEscrow public veWasabi;
uint256 public rewardRate;
// Info of each pool.
PoolInfo[] public poolInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
bool public mintWasabi;
uint256[] public feeLevel; // fixed length = 9 (unit without 10^18); [50,200,500,1000,2000,3500,6000,9000,11000]
uint256[] public discountTable; // fixed length = 9; [9,19,28,40,50,60,70,80,90]
uint256 public withdrawFee;
uint256 private constant hundred = 100;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev The address of the account which can perform emergency activities
address public sentinel;
address public withdrawFeeCollector;
bool public pause;
event PoolCreated(
uint256 indexed poolId,
IERC20 indexed token
);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Claim(address indexed user, uint256 indexed pid, uint256 amount);
event WorkingAmountUpdate(
address indexed user,
uint256 indexed pid,
uint256 newWorkingAmount,
uint256 newWorkingSupply
);
event PendingGovernanceUpdated(
address pendingGovernance
);
event GovernanceUpdated(
address governance
);
event WithdrawFeeCollectorUpdated(
address withdrawFeeCollector
);
event RewardVestingUpdated(
IRewardVesting rewardVesting
);
event PauseUpdated(
bool status
);
event SentinelUpdated(
address sentinel
);
event RewardRateUpdated(
uint256 rewardRate
);
// solium-disable-next-line
constructor(address _governance, address _sentinel,address _withdrawFeeCollector) public {
require(_governance != address(0), "StakingPoolsV4: governance address cannot be 0x0");
require(_sentinel != address(0), "StakingPoolsV4: sentinel address cannot be 0x0");
require(_withdrawFeeCollector != address(0), "StakingPoolsV4: withdrawFee collector address cannot be 0x0");
governance = _governance;
sentinel = _sentinel;
withdrawFeeCollector = _withdrawFeeCollector;
feeLevel = [50,200,500,1000,2000,3500,6000,9000,11000];
discountTable = [10,20,30,40,50,60,72,81,91];
withdrawFee = 20;
}
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPoolsV4: only governance");
_;
}
///@dev modifier add users to userlist. Users are indexed in order to keep track of
modifier checkIfNewUser(uint256 pid) {
if (!userIsKnown[msg.sender][pid]) {
userList[nextUser[pid]][pid] = msg.sender;
userIsKnown[msg.sender][pid] = true;
nextUser[pid]++;
}
_;
}
function initialize(
IMintableERC20 _rewardToken,
IVotingEscrow _veWasabi,
IRewardVesting _rewardVesting,
bool _mintWasabi
)
external
onlyGovernance
{
reward = _rewardToken;
veWasabi = _veWasabi;
rewardVesting = _rewardVesting;
mintWasabi = _mintWasabi;
}
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPoolsV4: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPoolsV4: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _needVesting,
uint256 _earlyWithdrawFee,
uint256 _withdrawLock,
bool _veBoostEnabled,
bool _withUpdate
)
public
onlyGovernance
{
if (_withUpdate) {
massUpdatePools();
}
uint256 poolId = poolInfo.length;
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0,
workingSupply: 0,
totalDeposited: 0,
needVesting:_needVesting,
earlyWithdrawFee:_earlyWithdrawFee,
withdrawLock:_withdrawLock,
veBoostEnabled:_veBoostEnabled
}));
emit PoolCreated(poolId, _lpToken);
}
// Update the given pool's SMTY allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
)
public
onlyGovernance
{
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
massUpdatePools();
rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
// Return block rewards over the given _from (inclusive) to _to (inclusive) block.
function getBlockReward(uint256 _from, uint256 _to) public view returns (uint256) {
uint256 to = _to;
uint256 from = _from;
if (from > to) {
return 0;
}
uint256 rewardPerBlock = rewardRate;
uint256 totalRewards = (to.sub(from)).mul(rewardPerBlock);
return totalRewards;
}
// View function to see pending SMTYs on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = pool.userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 workingSupply = pool.workingSupply;
if (block.number > pool.lastRewardBlock && workingSupply != 0) {
uint256 wasabiReward = getBlockReward(pool.lastRewardBlock, block.number).mul(
pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(wasabiReward.mul(1e18).div(workingSupply));
}
return user.workingAmount.mul(accRewardPerShare).div(1e18).sub(user.rewardDebt);
}
// View Accumulated Power
function accumulatedPower(address _user, uint256 _pid) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = pool.userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 workingSupply = pool.workingSupply;
if (block.number > pool.lastRewardBlock && workingSupply != 0) {
uint256 wasabiReward = getBlockReward(pool.lastRewardBlock, block.number).mul(
pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(wasabiReward.mul(1e18).div(workingSupply));
}
return user.power.add(user.workingAmount.mul(accRewardPerShare).div(1e18).sub(user.rewardDebt));
}
function getPoolUser(uint256 _poolId, uint256 _userIndex) external view returns (address) {
return userList[_userIndex][_poolId];
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
_updatePool(_pid);
}
function _updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 workingSupply = pool.workingSupply;
if (workingSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 wasabiReward = getBlockReward(pool.lastRewardBlock, block.number).mul(
pool.allocPoint).div(totalAllocPoint);
if (mintWasabi) {
reward.mint(address(this), wasabiReward);
}
pool.accRewardPerShare = pool.accRewardPerShare.add(wasabiReward.mul(1e18).div(workingSupply));
pool.lastRewardBlock = block.number;
}
modifier claimReward(uint256 _pid, address _account) {
require(!pause, "StakingPoolsV4: emergency pause enabled");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = pool.userInfo[_account];
_updatePool(_pid);
if (user.workingAmount > 0) {
uint256 rewardPending = user.workingAmount.mul(pool.accRewardPerShare).div(1e18).sub(user.rewardDebt);
if(pool.needVesting){
reward.approve(address(rewardVesting),uint(-1));
rewardVesting.addEarning(_account,rewardPending);
} else {
safeWasabiTransfer(_account, rewardPending);
}
user.power = user.power.add(rewardPending);
}
_; // amount/boost may be changed
_updateWorkingAmount(_pid, _account);
user.rewardDebt = user.workingAmount.mul(pool.accRewardPerShare).div(1e18);
}
function _updateWorkingAmount(
uint256 _pid,
address _account
) internal
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = pool.userInfo[_account];
uint256 lim = user.amount.mul(4).div(10);
uint256 votingBalance = veWasabi.balanceOf(_account);
uint256 totalBalance = veWasabi.totalSupply();
if (totalBalance != 0 && pool.veBoostEnabled) {
uint256 lsupply = pool.totalDeposited;
lim = lim.add(lsupply.mul(votingBalance).div(totalBalance).mul(6).div(10));
}
uint256 veAmount = Math.min(user.amount, lim);
pool.workingSupply = pool.workingSupply.sub(user.workingAmount).add(veAmount);
user.workingAmount = veAmount;
emit WorkingAmountUpdate(_account, _pid, user.workingAmount, pool.workingSupply);
}
/*
* Deposit without lock.
*/
function deposit(uint256 _pid, uint256 _amount) external nonReentrant claimReward(_pid, msg.sender) checkIfNewUser(_pid) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = pool.userInfo[msg.sender];
if (_amount > 0) {
_depositedAt[msg.sender][_pid] = block.timestamp;
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
pool.totalDeposited = pool.totalDeposited.add(_amount);
}
emit Deposit(msg.sender, _pid, _amount);
}
function setFeeLevel(uint256[] calldata _feeLevel) external onlyGovernance {
require(_feeLevel.length == 9, "StakingPoolsV4: feeLevel length mismatch");
feeLevel = _feeLevel;
}
function setDiscountTable(uint256[] calldata _discountTable) external onlyGovernance {
require(_discountTable.length == 9, "StakingPoolsV4: discountTable length mismatch");
discountTable = _discountTable;
}
function setWithdrawFee(uint256 _withdrawFee) external onlyGovernance {
withdrawFee = _withdrawFee;
}
function withdraw(uint256 _pid, uint256 amount) external nonReentrant {
_withdraw(_pid, amount);
}
function _withdraw(uint256 _pid, uint256 amount) internal claimReward(_pid, msg.sender) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = pool.userInfo[msg.sender];
require(amount <= user.amount, "StakingPoolsV4: withdraw too much");
pool.totalDeposited = pool.totalDeposited.sub(amount);
user.amount = user.amount - amount;
uint256 withdrawPenalty = 0;
uint256 finalizedAmount = amount;
uint256 depositTimestamp = _depositedAt[msg.sender][_pid];
if (depositTimestamp.add(pool.withdrawLock) > block.timestamp) {
withdrawPenalty = amount.mul(pool.earlyWithdrawFee).div(10000);
pool.lpToken.safeTransfer(withdrawFeeCollector, withdrawPenalty);
finalizedAmount = finalizedAmount.sub(withdrawPenalty);
} else {
uint256 votingBalance = veWasabi.balanceOf(msg.sender);
withdrawPenalty = amount.mul(withdrawFee).div(10000);
for (uint256 i = 0; i < 9; ++i) {
if(votingBalance >= (feeLevel[i]).mul(1 ether)){
withdrawPenalty = amount.mul(withdrawFee).div(10000);
withdrawPenalty = withdrawPenalty.mul(hundred.sub(discountTable[i])).div(hundred);
}
}
pool.lpToken.safeTransfer(withdrawFeeCollector, withdrawPenalty);
finalizedAmount = finalizedAmount.sub(withdrawPenalty);
}
pool.lpToken.safeTransfer(msg.sender, finalizedAmount);
emit Withdraw(msg.sender, _pid, amount);
}
// solium-disable-next-line
function claim(uint256 _pid) external nonReentrant claimReward(_pid, msg.sender) {
}
// Safe smty transfer function, just in case if rounding error causes pool to not have enough SMTYs.
function safeWasabiTransfer(address _to, uint256 _amount) internal {
if (_amount > 0) {
uint256 wasabiBal = reward.balanceOf(address(this));
if (_amount > wasabiBal) {
reward.transfer(_to, wasabiBal);
} else {
reward.transfer(_to, _amount);
}
}
}
function getUserInfo(address _account, uint256 _poolId) public view returns(uint, uint, uint) {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = pool.userInfo[_account];
return (user.amount, user.workingAmount, user.rewardDebt);
}
function getDepositedAt(address _account, uint256 _poolId) external view returns (uint256) {
return _depositedAt[_account][_poolId];
}
/// @dev Updates the reward vesting contract
///
/// @param _rewardVesting the new reward vesting contract
function setRewardVesting(IRewardVesting _rewardVesting) external {
require(pause && (msg.sender == governance || msg.sender == sentinel), "StakingPoolsV4: not paused, or not governance or sentinel");
rewardVesting = _rewardVesting;
emit RewardVestingUpdated(_rewardVesting);
}
/// @dev Sets the address of the sentinel
///
/// @param _sentinel address of the new sentinel
function setSentinel(address _sentinel) external onlyGovernance {
require(_sentinel != address(0), "StakingPoolsV4: sentinel address cannot be 0x0.");
sentinel = _sentinel;
emit SentinelUpdated(_sentinel);
}
/// @dev Sets if the contract should enter emergency pause mode.
///
/// There are 2 main reasons to pause:
/// 1. Need to shut down claims in case of any issues in the reward vesting contract
/// 2. Need to migrate to a new reward vesting contract
///
/// While this contract is paused, claim is disabled
///
/// @param _pause if the contract should enter emergency pause mode.
function setPause(bool _pause) external {
require(msg.sender == governance || msg.sender == sentinel, "StakingPoolsV4: !(gov || sentinel)");
pause = _pause;
emit PauseUpdated(_pause);
}
function setWithdrawFeeCollector(address _newWithdrawFeeCollector) external onlyGovernance {
require(_newWithdrawFeeCollector != address(0), "StakingPoolsV4: withdrawFeeCollector address cannot be 0x0.");
withdrawFeeCollector = _newWithdrawFeeCollector;
emit WithdrawFeeCollectorUpdated(_newWithdrawFeeCollector);
}
} | Sets the address of the sentinel _sentinel address of the new sentinel | function setSentinel(address _sentinel) external onlyGovernance {
require(_sentinel != address(0), "StakingPoolsV4: sentinel address cannot be 0x0.");
sentinel = _sentinel;
emit SentinelUpdated(_sentinel);
}
| 7,216,449 |
./full_match/5/0xaF58A878F9D9E4580476936EEB1Cb7D5Dd18cA7d/sources/contracts/ERC721A.sol | Equivalent to `_safeMint(to, quantity, '')`./ | function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
| 11,592,016 |
./full_match/11155111/0x5D6B8d8d7715b8Bf8eBe76f75BC55Cb1d6b24Ce1/sources/contracts/LotteryFactory.sol | Create a new subscription when the contract is initially deployed. Add this contract as a consumer of its own subscription. | function createNewSubscription() private onlyOwner {
chainlinkSubscriptionId = COORDINATOR.createSubscription();
COORDINATOR.addConsumer(chainlinkSubscriptionId, address(this));
}
| 3,794,269 |
pragma solidity ^0.5.8;
import "./IERC20.sol";
import "./SoraToken.sol";
/**
* Provides functionality of master contract
*/
contract Master {
bool internal initialized_;
address public owner_;
mapping(address => bool) public isPeer;
uint public peersCount;
/** Iroha tx hashes used */
mapping(bytes32 => bool) public used;
mapping(address => bool) public uniqueAddresses;
/** registered client addresses */
mapping(address => bytes) public registeredClients;
SoraToken public xorTokenInstance;
mapping(address => bool) public isToken;
/**
* Emit event on new registration with iroha acountId
*/
event IrohaAccountRegistration(address ethereumAddress, bytes accountId);
/**
* Emit event when master contract does not have enough assets to proceed withdraw
*/
event InsufficientFundsForWithdrawal(address asset, address recipient);
/**
* Constructor. Sets contract owner to contract creator.
*/
constructor(address[] memory initialPeers) public {
initialize(msg.sender, initialPeers);
}
/**
* Initialization of smart contract.
*/
function initialize(address owner, address[] memory initialPeers) public {
require(!initialized_);
owner_ = owner;
for (uint8 i = 0; i < initialPeers.length; i++) {
addPeer(initialPeers[i]);
}
// 0 means ether which is definitely in whitelist
isToken[address(0)] = true;
// Create new instance of Sora token
xorTokenInstance = new SoraToken();
isToken[address(xorTokenInstance)] = true;
initialized_ = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == owner_;
}
/**
* A special function-like stub to allow ether accepting
*/
function() external payable {
require(msg.data.length == 0);
}
/**
* Adds new peer to list of signature verifiers. Can be called only by contract owner.
* @param newAddress address of new peer
*/
function addPeer(address newAddress) private returns (uint) {
require(isPeer[newAddress] == false);
isPeer[newAddress] = true;
++peersCount;
return peersCount;
}
function removePeer(address peerAddress) private {
require(isPeer[peerAddress] == true);
isPeer[peerAddress] = false;
--peersCount;
}
function addPeerByPeer(
address newPeerAddress,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public returns (bool)
{
require(used[txHash] == false);
require(checkSignatures(keccak256(abi.encodePacked(newPeerAddress, txHash)),
v,
r,
s)
);
addPeer(newPeerAddress);
used[txHash] = true;
return true;
}
function removePeerByPeer(
address peerAddress,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public returns (bool)
{
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(peerAddress, txHash)),
v,
r,
s)
);
removePeer(peerAddress);
used[txHash] = true;
return true;
}
/**
* Adds new token to whitelist. Token should not been already added.
* @param newToken token to add
*/
function addToken(address newToken) public onlyOwner {
require(isToken[newToken] == false);
isToken[newToken] = true;
}
/**
* Checks is given token inside a whitelist or not
* @param tokenAddress address of token to check
* @return true if token inside whitelist or false otherwise
*/
function checkTokenAddress(address tokenAddress) public view returns (bool) {
return isToken[tokenAddress];
}
/**
* Register a clientIrohaAccountId for the caller clientEthereumAddress
* @param clientEthereumAddress - ethereum address to register
* @param clientIrohaAccountId - iroha account id
* @param txHash - iroha tx hash of registration
* @param v array of signatures of tx_hash (v-component)
* @param r array of signatures of tx_hash (r-component)
* @param s array of signatures of tx_hash (s-component)
*/
function register(
address clientEthereumAddress,
bytes memory clientIrohaAccountId,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
)
public
{
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(clientEthereumAddress, clientIrohaAccountId, txHash)),
v,
r,
s)
);
require(clientEthereumAddress == msg.sender);
require(registeredClients[clientEthereumAddress].length == 0);
registeredClients[clientEthereumAddress] = clientIrohaAccountId;
emit IrohaAccountRegistration(clientEthereumAddress, clientIrohaAccountId);
}
/**
* Withdraws specified amount of ether or one of ERC-20 tokens to provided address
* @param tokenAddress address of token to withdraw (0 for ether)
* @param amount amount of tokens or ether to withdraw
* @param to target account address
* @param txHash hash of transaction from Iroha
* @param v array of signatures of tx_hash (v-component)
* @param r array of signatures of tx_hash (r-component)
* @param s array of signatures of tx_hash (s-component)
* @param from relay contract address
*/
function withdraw(
address tokenAddress,
uint256 amount,
address payable to,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s,
address from
)
public
{
require(checkTokenAddress(tokenAddress));
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(tokenAddress, amount, to, txHash, from)),
v,
r,
s)
);
if (tokenAddress == address (0)) {
if (address(this).balance < amount) {
emit InsufficientFundsForWithdrawal(tokenAddress, to);
} else {
used[txHash] = true;
// untrusted transfer, relies on provided cryptographic proof
to.transfer(amount);
}
} else {
IERC20 coin = IERC20(tokenAddress);
if (coin.balanceOf(address (this)) < amount) {
emit InsufficientFundsForWithdrawal(tokenAddress, to);
} else {
used[txHash] = true;
// untrusted call, relies on provided cryptographic proof
coin.transfer(to, amount);
}
}
}
/**
* Checks given addresses for duplicates and if they are peers signatures
* @param hash unsigned data
* @param v v-component of signature from hash
* @param r r-component of signature from hash
* @param s s-component of signature from hash
* @return true if all given addresses are correct or false otherwise
*/
function checkSignatures(bytes32 hash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s
) private returns (bool) {
require(peersCount >= 1);
require(v.length == r.length);
require(r.length == s.length);
uint needSigs = peersCount - (peersCount - 1) / 3;
require(s.length >= needSigs);
uint count = 0;
address[] memory recoveredAddresses = new address[](s.length);
for (uint i = 0; i < s.length; ++i) {
address recoveredAddress = recoverAddress(
hash,
v[i],
r[i],
s[i]
);
// not a peer address or not unique
if (isPeer[recoveredAddress] != true || uniqueAddresses[recoveredAddress] == true) {
continue;
}
recoveredAddresses[count] = recoveredAddress;
count = count + 1;
uniqueAddresses[recoveredAddress] = true;
}
// restore state for future usages
for (uint i = 0; i < count; ++i) {
uniqueAddresses[recoveredAddresses[i]] = false;
}
return count >= needSigs;
}
/**
* Recovers address from a given single signature
* @param hash unsigned data
* @param v v-component of signature from hash
* @param r r-component of signature from hash
* @param s s-component of signature from hash
* @return address recovered from signature
*/
function recoverAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) private pure returns (address) {
bytes32 simple_hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
address res = ecrecover(simple_hash, v, r, s);
return res;
}
/**
* Mint new XORToken
* @param tokenAddress address to mint
* @param amount how much to mint
* @param beneficiary destination address
* @param txHash hash of transaction from Iroha
* @param v array of signatures of tx_hash (v-component)
* @param r array of signatures of tx_hash (r-component)
* @param s array of signatures of tx_hash (s-component)
*/
function mintTokensByPeers(
address tokenAddress,
uint256 amount,
address beneficiary,
bytes32 txHash,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s,
address from
)
public
{
require(address(xorTokenInstance) == tokenAddress);
require(used[txHash] == false);
require(checkSignatures(
keccak256(abi.encodePacked(tokenAddress, amount, beneficiary, txHash, from)),
v,
r,
s)
);
xorTokenInstance.mintTokens(beneficiary, amount);
used[txHash] = true;
}
}
| Recovers address from a given single signature hash unsigned data v v-component of signature from hash r r-component of signature from hash s s-component of signature from hash return address recovered from signature/ | function recoverAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) private pure returns (address) {
bytes32 simple_hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
address res = ecrecover(simple_hash, v, r, s);
return res;
}
| 15,831,182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.