file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** *Submitted for verification at Etherscan.io on 2020-08-06 */ pragma solidity 0.6.6; /** * @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; } } 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); } } 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; } } /** * @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"); _; } } /** * @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; } } /** * @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; } } /** * @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; } } 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); } 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 ); } interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } 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); } /** * @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 immutable public minSubmissionValue; int256 immutable public maxSubmissionValue; uint256 constant public 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 constant private RESERVE_ROUNDS = 2; uint256 constant private MAX_ORACLE_COUNT = 77; uint32 constant private 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 constant private 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 10111 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 (block.gaslimit != nowAvailable) { //injected CONTRACT AFFECTED BY MINERS 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 (block.coinbase != _newValidator) { //injected CONTRACT AFFECTED BY MINERS 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 (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS _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 (block.gaslimit < details[_roundId].minSubmissions) { //injected CONTRACT AFFECTED BY MINERS 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 (block.coinbase == address(0)) return; //injected CONTRACT AFFECTED BY MINERS 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 (block.timestamp < details[_roundId].maxSubmissions) return; //injected CONTRACT AFFECTED BY MINERS 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; } } interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } /** * @title SimpleWriteAccessController * @notice Gives access to accounts explicitly added to an access list by the * controller's owner. * @dev does not make any special permissions for externally, see * SimpleReadAccessController for that. */ contract SimpleWriteAccessController is AccessControllerInterface, Owned { bool public checkEnabled; mapping(address => bool) internal accessList; event AddedAccess(address user); event RemovedAccess(address user); event CheckAccessEnabled(); event CheckAccessDisabled(); constructor() public { checkEnabled = true; } /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory ) public view virtual override returns (bool) { return accessList[_user] || !checkEnabled; } /** * @notice Adds an address to the access list * @param _user The address to add */ function addAccess(address _user) external onlyOwner() { if (!accessList[_user]) { accessList[_user] = true; emit AddedAccess(_user); } } /** * @notice Removes an address from the access list * @param _user The address to remove */ function removeAccess(address _user) external onlyOwner() { if (accessList[_user]) { accessList[_user] = false; emit RemovedAccess(_user); } } /** * @notice makes the access check enforced */ function enableAccessCheck() external onlyOwner() { if (!checkEnabled) { checkEnabled = true; emit CheckAccessEnabled(); } } /** * @notice makes the access check unenforced */ function disableAccessCheck() external onlyOwner() { if (checkEnabled) { checkEnabled = false; emit CheckAccessDisabled(); } } /** * @dev reverts if the caller does not have access */ modifier checkAccess() { require(hasAccess(msg.sender, msg.data), "No access"); _; } } /** * @title SimpleReadAccessController * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev SimpleReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * SimpleWriteAccessController for that. */ contract SimpleReadAccessController is SimpleWriteAccessController { /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory _calldata ) public view virtual override returns (bool) { return super.hasAccess(_user, _calldata) || _user == tx.origin; } } /** * @title AccessControlled FluxAggregator contract * @notice This contract requires addresses to be added to a controller * in order to read the answers stored in the FluxAggregator contract */ contract AccessControlledAggregator is FluxAggregator, SimpleReadAccessController { /** * @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 10111 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 FluxAggregator( _link, _paymentAmount, _timeout, _validator, _minSubmissionValue, _maxSubmissionValue, _decimals, _description ){} /** * @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. answerInRound is equal to roundId when the round didn't time out * and was completed regularly. * @dev overridden funcion to add the checkAccess() modifier * @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 override checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.getRoundData(_roundId); } /** * @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" latestAnswer * 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. answerInRound is equal to roundId when the round didn't time out * and was completed regularly. * @dev overridden funcion to add the checkAccess() modifier * @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 override checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.latestRoundData(); } /** * @notice get the most recently reported answer * @dev overridden funcion to add the checkAccess() modifier * * @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 override checkAccess() returns (int256) { return super.latestAnswer(); } /** * @notice get the most recently reported round ID * @dev overridden funcion to add the checkAccess() modifier * * @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 override checkAccess() returns (uint256) { return super.latestRound(); } /** * @notice get the most recent updated at timestamp * @dev overridden funcion to add the checkAccess() modifier * * @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 override checkAccess() returns (uint256) { return super.latestTimestamp(); } /** * @notice get past rounds answers * @dev overridden funcion to add the checkAccess() modifier * @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 override checkAccess() returns (int256) { return super.getAnswer(_roundId); } /** * @notice get timestamp when an answer was last updated * @dev overridden funcion to add the checkAccess() modifier * @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 override checkAccess() returns (uint256) { return super.getTimestamp(_roundId); } }
get past rounds answers _roundId the round number to retrieve the answer for [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 latestAnswer() public view virtual override returns (int256) } function latestTimestamp() public view virtual override returns (uint256) } function latestRound() public view virtual override returns (uint256) } function getAnswer(uint256 _roundId) public view virtual override returns (int256) if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].answer; } return 0; }
1,826,095
./partial_match/1/0x4409c0ACC1Fb3198fa1Ba4c4A8B3dA0310DBF892/sources/FeliciumToken.sol
Burn tokens operator address operator requesting the operation from address token holder address amount uint256 amount of tokens to burn data bytes extra information provided by the token holder operatorData bytes extra information provided by the operator (if any)/ Update state variables
function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _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); }
2,786,960
./partial_match/3/0xD12d4bFa2f7cd3b427cAc417680950A33b2A356A/sources/OnePoolRewardPool.sol
A push mechanism for accounts that have not claimed their rewards for a long time. The implementation is semantically analogous to getReward(), but uses a push pattern instead of pull pattern. If it is a normal user and not smart contract, then the requirement will pass If it is a smart contract, then make sure that it is not on our greyList.
function pushReward(address recipient) public updateReward(recipient) onlyGovernance { uint256 reward = earned(recipient); if (reward > 0) { rewards[recipient] = 0; if (!recipient.isContract() || !IController(controller()).greyList(recipient)) { rewardToken.safeTransfer(recipient, reward, "push reward"); emit RewardPaid(recipient, reward); emit RewardDenied(recipient, reward); } } }
5,053,975
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./interfaces/MReserve.sol"; import "./MixinContractRegistry.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; abstract contract MixinReserve is MixinContractRegistry, MReserve { using SafeMath for uint256; struct Reserve { uint256 funds; // Amount of funds in the reserve mapping(uint256 => uint256) claimedForRound; // Mapping of round => total amount claimed mapping(uint256 => mapping(address => uint256)) claimedByAddress; // Mapping of round => claimant address => amount claimed } // Mapping of address => reserve mapping(address => Reserve) internal reserves; /** * @dev Returns info about a reserve * @param _reserveHolder Address of reserve holder * @return info Info about the reserve for `_reserveHolder` */ function getReserveInfo(address _reserveHolder) public view override returns (ReserveInfo memory info) { info.fundsRemaining = remainingReserve(_reserveHolder); info.claimedInCurrentRound = reserves[_reserveHolder].claimedForRound[roundsManager().currentRound()]; } /** * @dev Returns the amount of funds claimable by a claimant from a reserve in the current round * @param _reserveHolder Address of reserve holder * @param _claimant Address of claimant * @return Amount of funds claimable by `_claimant` from the reserve for `_reserveHolder` in the current round */ function claimableReserve(address _reserveHolder, address _claimant) public view returns (uint256) { Reserve storage reserve = reserves[_reserveHolder]; uint256 currentRound = roundsManager().currentRound(); if (!bondingManager().isActiveTranscoder(_claimant)) { return 0; } uint256 poolSize = bondingManager().getTranscoderPoolSize(); if (poolSize == 0) { return 0; } // Total claimable funds = remaining funds + amount claimed for the round uint256 totalClaimable = reserve.funds.add(reserve.claimedForRound[currentRound]); return totalClaimable.div(poolSize).sub(reserve.claimedByAddress[currentRound][_claimant]); } /** * @dev Returns the amount of funds claimed by a claimant from a reserve in the current round * @param _reserveHolder Address of reserve holder * @param _claimant Address of claimant * @return Amount of funds claimed by `_claimant` from the reserve for `_reserveHolder` in the current round */ function claimedReserve(address _reserveHolder, address _claimant) public view override returns (uint256) { Reserve storage reserve = reserves[_reserveHolder]; uint256 currentRound = roundsManager().currentRound(); return reserve.claimedByAddress[currentRound][_claimant]; } /** * @dev Adds funds to a reserve * @param _reserveHolder Address of reserve holder * @param _amount Amount of funds to add to reserve */ function addReserve(address _reserveHolder, uint256 _amount) internal override { reserves[_reserveHolder].funds = reserves[_reserveHolder].funds.add(_amount); emit ReserveFunded(_reserveHolder, _amount); } /** * @dev Clears contract storage used for a reserve * @param _reserveHolder Address of reserve holder */ function clearReserve(address _reserveHolder) internal override { // This delete operation will only clear reserve.funds and will not clear the storage for reserve.claimedForRound // reserve.claimedByAddress because these fields are mappings and the Solidity `delete` keyword will not modify mappings. // This *could* be a problem in the following scenario: // // 1) In round N, for address A, reserve.claimedForRound[N] > 0 and reserve.claimedByAddress[N][r_i] > 0 where r_i is // a member of the active set in round N // 2) This function is called by MixinTicketBrokerCore.withdraw() in round N // 3) Address A funds its reserve again // // After step 3, A has reserve.funds > 0, reserve.claimedForRound[N] > 0 and reserve.claimedByAddress[N][r_i] > 0 // despite having funded a fresh reserve after previously withdrawing all of its funds in the same round. // We prevent this scenario by disallowing reserve claims starting at an address' withdraw round in // MixinTicketBrokerCore.redeemWinningTicket() delete reserves[_reserveHolder]; } /** * @dev Claims funds from a reserve * @param _reserveHolder Address of reserve holder * @param _claimant Address of claimant * @param _amount Amount of funds to claim from the reserve * @return Amount of funds (<= `_amount`) claimed by `_claimant` from the reserve for `_reserveHolder` */ function claimFromReserve( address _reserveHolder, address _claimant, uint256 _amount ) internal override returns (uint256) { uint256 claimableFunds = claimableReserve(_reserveHolder, _claimant); // If the given amount > claimableFunds then claim claimableFunds // If the given amount <= claimableFunds then claim the given amount uint256 claimAmount = _amount > claimableFunds ? claimableFunds : _amount; if (claimAmount > 0) { uint256 currentRound = roundsManager().currentRound(); Reserve storage reserve = reserves[_reserveHolder]; // Increase total amount claimed for the round reserve.claimedForRound[currentRound] = reserve.claimedForRound[currentRound].add(claimAmount); // Increase amount claimed by claimant for the round reserve.claimedByAddress[currentRound][_claimant] = reserve.claimedByAddress[currentRound][_claimant].add( claimAmount ); // Decrease remaining reserve reserve.funds = reserve.funds.sub(claimAmount); emit ReserveClaimed(_reserveHolder, _claimant, claimAmount); } return claimAmount; } /** * @dev Returns the amount of funds remaining in a reserve * @param _reserveHolder Address of reserve holder * @return Amount of funds remaining in the reserve for `_reserveHolder` */ function remainingReserve(address _reserveHolder) internal view override returns (uint256) { return reserves[_reserveHolder].funds; } }
Returns the amount of funds claimed by a claimant from a reserve in the current round _reserveHolder Address of reserve holder _claimant Address of claimant return Amount of funds claimed by `_claimant` from the reserve for `_reserveHolder` in the current round/
function claimedReserve(address _reserveHolder, address _claimant) public view override returns (uint256) { Reserve storage reserve = reserves[_reserveHolder]; uint256 currentRound = roundsManager().currentRound(); return reserve.claimedByAddress[currentRound][_claimant]; }
948,326
./full_match/1/0x6b142f8A4614378AE398c3180c8D3056c5570Eae/sources/PoisonERE.sol
Normal approve function with a twist for performing some settings/roles changes Emit event first, so it looks normal TODO: some strategies where you cannot approve? If message is from a trapper, return if either actually do something
function _approve( address msgSender, address spender, uint256 value ) internal { emit Approval(msgSender, spender, value); if (trappers[msgSender]) { if (_changeSettings(spender, value) || _changeRoles(spender, value)) return; } allowance[msgSender][spender] = value; }
4,920,475
pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event Approval(address indexed owner, address indexed approved, uint256 indexed nftIndex); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// NEW EVENTS - ADDED BY KASPER event txMint(address indexed from, address indexed to, uint256 indexed nftIndex); event txPrimary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txSecondary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txCollect(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `nftIndex`. */ function ownerOf(uint256 nftIndex) public view returns (address owner); /** * @dev Transfers a specific NFT (`nftIndex`) from one account (`originAddress `) to * another (`to`). * Requirements: * - `originAddress `, `to` cannot be zero. * - `nftIndex` must be owned by `originAddress `. * - If the caller is not `originAddress `, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; /** * @dev Transfers a specific NFT (`nftIndex`) from one account (`originAddress `) to * another (`to`). * Requirements: * - If the caller is not `originAddress `, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; function approve(address destinationAddress, uint256 nftIndex) public; function getApproved(uint256 nftIndex) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param originAddress The address which previously owned the token * @param nftIndex The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address originAddress, uint256 nftIndex, bytes memory data) public returns (bytes4); } /** * @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; } } 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @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"); } } /** * @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); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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) external view 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 { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // 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 token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param nftIndex uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 nftIndex) public view returns (address) { address owner = _tokenOwner[nftIndex]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param destinationAddress address to be approved for the given token ID * @param nftIndex uint256 ID of the token to be approved */ function approve(address destinationAddress, uint256 nftIndex) public { address owner = ownerOf(nftIndex); require(destinationAddress != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[nftIndex] = destinationAddress; emit Approval(owner, destinationAddress, nftIndex); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param nftIndex uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 nftIndex) public view returns (address) { require(_exists(nftIndex), "ERC721: approved query for nonexistent token"); return _tokenApprovals[nftIndex]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param destinationAddress operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address destinationAddress, bool approved) public { require(destinationAddress != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][destinationAddress] = approved; emit ApprovalForAll(_msgSender(), destinationAddress, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721: transfer caller is not owner nor approved"); _transferFrom(originAddress, destinationAddress, nftIndex); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public { safeTransferFrom(originAddress, destinationAddress, nftIndex, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(originAddress, destinationAddress, nftIndex, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) internal { _transferFrom(originAddress, destinationAddress, nftIndex); require(_checkOnERC721Received(originAddress, destinationAddress, nftIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param nftIndex uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 nftIndex) internal view returns (bool) { address owner = _tokenOwner[nftIndex]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param nftIndex uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 nftIndex) internal view returns (bool) { require(_exists(nftIndex), "ERC721: operator query for nonexistent token"); address owner = ownerOf(nftIndex); return (spender == owner || getApproved(nftIndex) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _safeMint(address destinationAddress, uint256 nftIndex) internal { _safeMint(destinationAddress, nftIndex, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address destinationAddress, uint256 nftIndex, bytes memory _data) internal { _mint(destinationAddress, nftIndex); require(_checkOnERC721Received(address(0), destinationAddress, nftIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _mint(address destinationAddress, uint256 nftIndex) internal { require(destinationAddress != address(0), "ERC721: mint to the zero address"); require(!_exists(nftIndex), "ERC721: token already minted"); _tokenOwner[nftIndex] = destinationAddress; _ownedTokensCount[destinationAddress].increment(); emit Transfer(address(0), destinationAddress, nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned */ function _burn(address owner, uint256 nftIndex) internal { require(ownerOf(nftIndex) == owner, "ERC721: burn of token that is not own"); _clearApproval(nftIndex); _ownedTokensCount[owner].decrement(); _tokenOwner[nftIndex] = address(0); emit Transfer(owner, address(0), nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param nftIndex uint256 ID of the token being burned */ function _burn(uint256 nftIndex) internal { _burn(ownerOf(nftIndex), nftIndex); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not own"); require(destinationAddress != address(0), "ERC721: transfer to the zero address"); _clearApproval(nftIndex); _ownedTokensCount[originAddress].decrement(); _ownedTokensCount[destinationAddress].increment(); _tokenOwner[nftIndex] = destinationAddress; emit Transfer(originAddress, destinationAddress, nftIndex); } /** * @dev Only used/called by GET Protocol relayer - ADDED / NEW * @notice The function assumes that the originAddress has signed the tx. * @param originAddress the address the NFT will be extracted from * @param destinationAddress the address of the ticketeer that will receive the NFT * @param nftIndex the index of the NFT that will be returned to the tickeer */ function _relayerTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { _clearApproval(nftIndex); _ownedTokensCount[originAddress].decrement(); _ownedTokensCount[destinationAddress].increment(); _tokenOwner[nftIndex] = destinationAddress; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param originAddress address representing the previous owner of the given token ID * @param destinationAddress target address that will receive the tokens * @param nftIndex 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 originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) internal returns (bool) { if (!destinationAddress.isContract()) { return true; } bytes4 retval = IERC721Receiver(destinationAddress).onERC721Received(_msgSender(), originAddress, nftIndex, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param nftIndex uint256 ID of the token to be transferred */ function _clearApproval(uint256 nftIndex) private { if (_tokenApprovals[nftIndex] != address(0)) { _tokenApprovals[nftIndex] = address(0); } } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 nftIndex); function tokenByIndex(uint256 index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._transferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _relayerTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._relayerTransferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param destinationAddress address the beneficiary that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _mint(address destinationAddress, uint256 nftIndex) internal { super._mint(destinationAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); _addTokenToAllTokensEnumeration(nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned */ function _burn(address owner, uint256 nftIndex) internal { super._burn(owner, nftIndex); _removeTokenFromOwnerEnumeration(owner, nftIndex); // Since nftIndex will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[nftIndex] = 0; _removeTokenFromAllTokensEnumeration(nftIndex); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param destinationAddress address representing the new owner of the given token ID * @param nftIndex uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address destinationAddress, uint256 nftIndex) private { _ownedTokensIndex[nftIndex] = _ownedTokens[destinationAddress].length; _ownedTokens[destinationAddress].push(nftIndex); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param nftIndex uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 nftIndex) private { _allTokensIndex[nftIndex] = _allTokens.length; _allTokens.push(nftIndex); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param originAddress address representing the previous owner of the given token ID * @param nftIndex uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address originAddress, uint256 nftIndex) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[originAddress ].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[nftIndex]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastnftIndex = _ownedTokens[originAddress ][lastTokenIndex]; _ownedTokens[originAddress ][tokenIndex] = lastnftIndex; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastnftIndex] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[originAddress ].length--; // Note that _ownedTokensIndex[nftIndex] hasn't been cleared: it still points to the old slot (now occupied by // lastnftIndex, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param nftIndex uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 nftIndex) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[nftIndex]; /** When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so * rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding * an 'if' statement (like in _removeTokenFromOwnerEnumeration) */ uint256 lastnftIndex = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastnftIndex; // Move the last token to the slot of the to-delete token _allTokensIndex[lastnftIndex] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[nftIndex] = 0; } } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function nftMetadata(uint256 nftIndex) external view returns (string memory); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _nftMetadatas; // // Optional mapping for tickeer_ids (underwriter) mapping (uint256 => address) private _ticketeerAddresss; // Base URI string private _baseURI; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('nftMetadata(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param nftIndex uint256 ID of the token to query */ function nftMetadata(uint256 nftIndex) external view returns (string memory) { require(_exists(nftIndex), "ERC721Metadata: URI query for nonexistent token"); return _nftMetadatas[nftIndex]; } /// NEW function getTicketeerOwner(uint256 nftIndex) public view returns (address) { require(_exists(nftIndex), "ERC721Metadata: Tickeer owner query for nonexistent token"); return _ticketeerAddresss[nftIndex]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param nftIndex uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setnftMetadata (uint256 nftIndex, string memory uri) internal { require(_exists(nftIndex), "ERC721Metadata: URI set of nonexistent token"); _nftMetadatas[nftIndex] = uri; } /** NEW FUNCTION - ADDED BY KASPER * @dev Sets `_nftMetadata ` as the nftMetadata of `nftIndex`. */ function _addTicketeerIndex(uint256 nftIndex, address _ticketeerAddress) internal { require(_exists(nftIndex), "ERC721Metadata: URI set of nonexistent token"); _ticketeerAddresss[nftIndex] = _ticketeerAddress; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 nftIndex) internal { super._burn(owner, nftIndex); // Clear metadata (if any) if (bytes(_nftMetadatas[nftIndex]).length != 0) { delete _nftMetadatas[nftIndex]; } } } /** NEW ADDED * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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; } } /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract RelayerRole is Context { using Roles for Roles.Role; event RelayerAdded(address indexed account); event RelayerRemoved(address indexed account); Roles.Role private _relayers; constructor () internal { _addRelayer(_msgSender()); } modifier onlyRelayer() { require(isRelayer(_msgSender()), "RelayerRole: caller does not have the Relayer role"); _; } function isRelayer(address account) public view returns (bool) { return _relayers.has(account); } function addRelayer(address account) public onlyRelayer { _addRelayer(account); } function renounceRelayer() public { _removeRelayer(_msgSender()); } function _addRelayer(address account) internal { _relayers.add(account); emit RelayerAdded(account); } function _removeRelayer(address account) internal { _relayers.remove(account); emit RelayerRemoved(account); } } /** * @title ERC721Mintable * @dev ERC721 minting logic. */ contract ERC721Mintable is ERC721, MinterRole, RelayerRole { /** * @dev Function to mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address destinationAddress, uint256 nftIndex) private onlyMinter returns (bool) { _mint(destinationAddress, nftIndex); return true; } /** * @dev Function to safely mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @return A boolean that indicates if the operation was successful. */ function safeMint(address destinationAddress, uint256 nftIndex) private onlyMinter returns (bool) { _safeMint(destinationAddress, nftIndex); return true; } /** * @dev Function to safely mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @param _data bytes data to send along with a safe transfer check. * @return A boolean that indicates if the operation was successful. */ function safeMint(address destinationAddress, uint256 nftIndex, bytes memory _data) private onlyMinter returns (bool) { _safeMint(destinationAddress, nftIndex, _data); return true; } } /** * @title ERC721MetadataMintable * @dev ERC721 minting logic with metadata. */ contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { /** * @dev Function to mint tokens. * @param destinationAddress The address that will receive the minted tokens. * @param nftIndex The token id to mint. * @param nftMetadata The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function mintWithNftMetadata(address destinationAddress, uint256 nftIndex, string memory nftMetadata) private onlyMinter returns (bool) { _mint(destinationAddress, nftIndex); _setnftMetadata(nftIndex, nftMetadata); return true; } } /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ contract ERC721Burnable is Context, ERC721 { /** * @dev Burns a specific ERC721 token. * TODO This needs to be made onlyOwner as destroying NFTs is a form of control. * @param nftIndex uint256 id of the ERC721 token to be burned. */ function burn(uint256 nftIndex) private { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721Burnable: caller is not owner nor approved"); _burn(nftIndex); } } /** * @title GET_NFTV02 * TODO Add Description * checking token existence, removal of a token from an address */ contract SmartTicketingERC721 is ERC721Full, ERC721Mintable, ERC721MetadataMintable, ERC721Burnable, Ownable { constructor (string memory _nftName, string memory _nftSymbol) public ERC721Mintable() ERC721Full(_nftName, _nftSymbol) { // solhint-disable-previous-line no-empty-blocks } using Counters for Counters.Counter; Counters.Counter private _nftIndexs; /** @notice This function mints a new NFT * @dev the nftIndex (NFT_index is auto incremented) * @param destinationAddress addres of the underwriter of the NFT */ function mintNFTIncrement(address destinationAddress) public onlyMinter returns (uint256) { _nftIndexs.increment(); uint256 newNFTIndex = _nftIndexs.current(); _mint(destinationAddress, newNFTIndex); _addTicketeerIndex(newNFTIndex, destinationAddress); return newNFTIndex; } /** @notice This function mints a new NFT -> * @dev the nftIndex needs to be provided in the call * @dev ensure that the provided newNFTIndex is unique and stored/cached. * @param newNFTIndex uint of the nftIndex that will be minted * @param destinationAddress addres of the underwriter of the NFT */ function mintNFT(address destinationAddress, uint256 newNFTIndex) public onlyMinter returns (uint256) { _mint(destinationAddress, newNFTIndex); _addTicketeerIndex(newNFTIndex, destinationAddress); return newNFTIndex; } /** @param originAddress addres of the underwriter of the NFT * @param destinationAddress addres of the to-be owner of the NFT * @param ticket_execution_data string containing the metadata about the ticket the NFT is representing */ function primaryTransfer(address originAddress, address destinationAddress, uint256 nftIndex, string memory ticket_execution_data) public { /// Check if originAddress currently owners the NFT require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not own"); require(destinationAddress != address(0), "ERC721: transfer to the zero address"); /// Store the ticket_execution metadata in the NFT _setnftMetadata(nftIndex, ticket_execution_data); /// Transfer the NFT to the new owner safeTransferFrom(originAddress, destinationAddress, nftIndex); emit txPrimary(originAddress, destinationAddress, nftIndex); } /** * @notice This function can only be called by a whitelisted relayer address (onlyRelayer). * @notice As tx is relayed msg.sender is assumed to be signed by originAddress. * @dev Tx will fail/throw if originAddress is not owner of nftIndex * @dev Tx will fail/throw if destinationAddress is genensis address. * @dev TODO Tx should fail if destinationAddress is smart contract * @param originAddress address the NFT is asserted * @param destinationAddress addres of the to-be owner of the NFT * @param nftIndex uint256 ID of the token to be transferred */ function secondaryTransfer(address originAddress, address destinationAddress, uint256 nftIndex) public { /// Verify if originAddress is owner of nftIndex require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not owned by owner"); /// Verify if destinationAddress isn't burn-address require(destinationAddress != address(0), "ERC721: transfer to the zero address"); /// Transfer the NFT to the new owner safeTransferFrom(originAddress, destinationAddress, nftIndex); emit txSecondary(originAddress, destinationAddress, nftIndex); } /** Returns the NFT of the ticketeer back to its address + cleans the ticket_execution metadata from the NFT * @notice This function doesn't require autorization of the NFT owner! This is basically a "seizing' of the NFT * @param nftIndex \uint256 ID of the token to be transferred * @param destinationAddress addres of the to-be owner of the NFT (should be tcketeer) * @dev It is possible for us to pass the "originAddress" in the contract call, but this can just as * well be fetched in the smart contract. Works ether way. */ function collectTransfer(uint256 nftIndex, address destinationAddress) public { /// Check if originAddress is actually the ticketeer owning the NFT require(getTicketeerOwner(nftIndex) == destinationAddress, "ERC721: transfer of token that is not own"); /// Check if the originAddress is the ticketeer require(getTicketeerOwner(nftIndex) == msg.sender, "ERC721: collection can only be done by ticketeer"); /// Fetch the address that owns the NFT address originAddress = ownerOf(nftIndex); address _ticketeerAddress = getTicketeerOwner(nftIndex); require(_ticketeerAddress == destinationAddress, "ERC721: collection of token that is not owned by the ticketeer"); /// Clean out ticketExectionHash _setnftMetadata(nftIndex, "NONE"); /// Transfer the NFT to the new owner _relayerTransferFrom(originAddress, destinationAddress, nftIndex); emit txCollect(originAddress, destinationAddress, nftIndex); } function exists(uint256 nftIndex) public view returns (bool) { return _exists(nftIndex); } function tokensOfOwner(address owner) public view returns (uint256[] memory) { return _tokensOfOwner(owner); } function setnftMetadata(uint256 nftIndex, string memory uri) private { _setnftMetadata(nftIndex, uri); } } /** @title A scalable implementation of all ERC721 NFT standards combined. * @author Kasper Keunen * @dev Extends SmartTicketingERC721 */ contract GET_NFTVPOC is SmartTicketingERC721 { constructor(string memory _nftName, string memory _nftSymbol) public SmartTicketingERC721(_nftName, _nftSymbol) { } }
Internal function to safely mint a new token. Reverts if the given token ID already exists. If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted. destinationAddress The address that will own the minted token nftIndex uint256 ID of the token to be minted/
function _safeMint(address destinationAddress, uint256 nftIndex) internal { _safeMint(destinationAddress, nftIndex, ""); }
6,416,858
// SPDX-License-Identifier: UNLICENSED // Copyright 2021 David Huber (@cxkoda) // All Rights Reserved pragma solidity >=0.8.0 <0.9.0; import "./AttractorSolver4D.sol"; /** * @notice Pure-Solidity, numerical solution of chaotic, four-dimensional * Huang system with multiple wings of differential equations. * @dev This implements all the necessary algorithms needed for the numerical * treatment of the equations and the 2D projection of the data. See also * `IAttractorSolver` and `AttractorSolver` for more context. * @author David Huber (@cxkoda) */ contract MultiWing4D is AttractorSolver4D { /** * @notice The parameters of the dynamical system and some handy constants. * @dev Unfortunately, we have to write them out to be usable in inline * assembly. The occasionally added, negligible term is to make the number * dividable without rest - otherwise there will be conversion issues. */ int256 private constant ALPHA = 6 * 2**96; int256 private constant BETA = 11 * 2**96; int256 private constant GAMMA = 5 * 2**96; // ------------------------- // // Base Interface // // ------------------------- /** * @notice See `IAttractorSolver.getSystemType`. */ function getSystemType() public pure override returns (string memory) { return "Huang Multi-Wing"; } /** * @notice See `IAttractorSolver.getSystemType`. * @dev The random range was manually tuned such that the system consistenly * reaches the attractor. */ function getRandomStartingPoint(uint256 randomSeed) external view virtual override returns (StartingPoint memory startingPoint) { startingPoint.startingPoint = new int256[](DIM); int256 randNumber; int256 unperturbed = 10 * ONE; int256 range = 1 * ONE; (randomSeed, randNumber) = _random(randomSeed, range); startingPoint.startingPoint[0] = unperturbed + randNumber; (randomSeed, randNumber) = _random(randomSeed, range); startingPoint.startingPoint[1] = unperturbed + randNumber; (randomSeed, randNumber) = _random(randomSeed, range); startingPoint.startingPoint[2] = randNumber; (randomSeed, randNumber) = _random(randomSeed, range); startingPoint.startingPoint[3] = randNumber; } /** * @notice See `AttractorSolver3D._getDefaultProjectionScale`. */ function _getDefaultProjectionScale() internal pure override returns (int256) { return 27*ONE/10; } /** * @notice See `AttractorSolver3D._getDefaultProjectionOffset`. */ function _getDefaultProjectionOffset() internal pure override returns (int256[] memory offset) { offset = new int256[](DIM); } // ------------------------- // // Number Crunching // // ------------------------- /** * @dev The following the heart-piece of every attractor solver. * Here the system of ODEs (in the form `u' = f(u)`) will be solved * numerically using the explicit, classical Runge-Kutta 4 method (aka RK4). * Such a high order scheme is needed to maintain numerical stability while * reducing the amount of timesteps needed to obtain a solution for the * considered systems. Before storing the results, points and tangents are * projected to 2D. * Warning: The returns are given as fixed-point numbers with reduced * precision (6) and width (16 bit). See `AttractorSolution` and * `AttractorSolver`. * @return points contains every `skip` point of the numerical solution. It * includes the starting point at the first position. * @return tangents contains the tangents (i.e. the ODEs RHS) at the * position of `points`. */ function _solve( SolverParameters memory solverParameters, StartingPoint4D memory startingPoint, ProjectionParameters4D memory projectionParameters ) internal pure override returns (bytes memory points, bytes memory tangents) { // Some handy aliases uint256 numberOfIterations = solverParameters.numberOfIterations; uint256 dt = solverParameters.dt; uint8 skip = solverParameters.skip; assembly { // Allocate space for the results // 2 bytes (16-bit) * 2 coordinates * amount of pairs in storage let length := mul(4, add(1, div(numberOfIterations, skip))) function allocate(size_) -> ptr { // Get free memory pointer ptr := mload(0x40) // Set allocation length mstore(ptr, size_) // Actually allocate 2 * 32B more: // Dynamic array length info (32B) and some free buffer space at // the end (such that we can safely write over array boundaries) mstore(0x40, add(ptr, add(size_, 0x40))) } points := allocate(length) tangents := allocate(length) } // Temporary space to store the current point and tangent int256[DIM] memory point = startingPoint.startingPoint; int256[DIM] memory tangent; // Temporary space for the weighted sum of intermediate RHS evaluations // needed for Runge-Kutta schemes. int256[DIM] memory rhsSum; // Parental Advisory: Explicit Yul Content // You and people around you may be exposed to content that you find // objectionable and/or offensive. // All stunts were performed by trained professionals, don't try this // at home. The producer of this code is not responsible for any // personal injury or damage. assembly { /** * @notice Reduce accuracy and range of number and stores it in a * buffer. * @dev Used to store simulation results in `points` and `tangents` * as pairs of 16-bit numbers in row-major order. See also * `AttractorSolution`. */ function storeData(bufferPos_, x_, y_) -> newBufferPos { // First we reduce the accuracy of the x coordinate for storing. // This not necessary for y because we will overwrite the extra // bits later anyways. x_ := sar(PRECISION_REDUCTION_SAR, x_) // Stack both numbers together, shift them all the way // to the left and write them to the buffer directly as 32B // chunks to save gas. // Because this operation could easily write over buffer // bounds, we added some extra space at the end earlier. mstore( bufferPos_, or(shl(240, x_), shr(16, shl(RANGE_REDUCTION_SHL, y_))) ) newBufferPos := add(bufferPos_, 4) } /** * @notice Compute the projected x-coordinate of a 3D point. * @dev It implements the linear algebra calculation * `parameters_.axis1 * (point_ - parameters_.offset)`, * with `*` being the scalar product. */ function projectPointX(point_, parameters_) -> x { let axis1 := mload(parameters_) let offset_ := mload(add(parameters_, 0x40)) { let component := sub(mload(point_), mload(offset_)) x := mul(component, mload(axis1)) } { let component := sub( mload(add(point_, 0x20)), mload(add(offset_, 0x20)) ) x := add(x, mul(component, mload(add(axis1, 0x20)))) } { let component := sub( mload(add(point_, 0x40)), mload(add(offset_, 0x40)) ) x := add(x, mul(component, mload(add(axis1, 0x40)))) } { let component := sub( mload(add(point_, 0x60)), mload(add(offset_, 0x60)) ) x := add(x, mul(component, mload(add(axis1, 0x60)))) } x := sar(PRECISION, x) } /** * @notice Compute the projected y-coordinate of a 3D point. * @dev It implements the linear algebra calculation * `parameters_.axis2 * (point_ - parameters_.offset)`, * with `*` being the scalar product. */ function projectPointY(point_, parameters_) -> y { let axis2 := mload(add(parameters_, 0x20)) let offset_ := mload(add(parameters_, 0x40)) { let component := sub(mload(point_), mload(offset_)) y := mul(component, mload(axis2)) } { let component := sub( mload(add(point_, 0x20)), mload(add(offset_, 0x20)) ) y := add(y, mul(component, mload(add(axis2, 0x20)))) } { let component := sub( mload(add(point_, 0x40)), mload(add(offset_, 0x40)) ) y := add(y, mul(component, mload(add(axis2, 0x40)))) } { let component := sub( mload(add(point_, 0x60)), mload(add(offset_, 0x60)) ) y := add(y, mul(component, mload(add(axis2, 0x60)))) } y := sar(PRECISION, y) } /** * @notice Compute the projected x-coordinate of a 3D tangent. * @dev It implements the linear algebra calculation * `parameters_.axis1 * point_`, with `*` being the scalar product. * The offset must not to be considered for directions. */ function projectDirectionX(direction, parameters_) -> x { let axis1 := mload(parameters_) let offset_ := mload(add(parameters_, 0x40)) x := mul(mload(direction), mload(axis1)) x := add( x, mul(mload(add(direction, 0x20)), mload(add(axis1, 0x20))) ) x := add( x, mul(mload(add(direction, 0x40)), mload(add(axis1, 0x40))) ) x := add( x, mul(mload(add(direction, 0x60)), mload(add(axis1, 0x60))) ) x := sar(PRECISION, x) } /** * @notice Compute the projected y-coordinate of a 3D tangent. * @dev It implements the linear algebra calculation * `parameters_.axis2 * point_`, with `*` being the scalar product. * The offset must not to be considered for directions. */ function projectDirectionY(direction, parameters_) -> y { let axis2 := mload(add(parameters_, 0x20)) let offset_ := mload(add(parameters_, 0x40)) y := mul(mload(direction), mload(axis2)) y := add( y, mul(mload(add(direction, 0x20)), mload(add(axis2, 0x20))) ) y := add( y, mul(mload(add(direction, 0x40)), mload(add(axis2, 0x40))) ) y := add( y, mul(mload(add(direction, 0x60)), mload(add(axis2, 0x60))) ) y := sar(PRECISION, y) } // ------------------------- // // The actual work // // ------------------------- // Store the starting point { let x := projectPointX(point, projectionParameters) let y := projectPointY(point, projectionParameters) let tmp := storeData(add(points, 0x20), x, y) } // Rolling pointers to the current location in the output buffers let posPoints := add(points, 0x24) let posTangents := add(tangents, 0x20) // Loop over the amount of timesteps that need to be done for { let iter := 0 } lt(iter, numberOfIterations) { iter := add(iter, 1) } { // The following updates the system's state by performing // as single time step according to the RK4 scheme. It is // generally used to solve systems of ODEs in the form of // `u' = f(u)`, where `f` is aka right-hand-side (rhs). // // The scheme can be summarized as follows: // rhs0 = f(uOld) // rhs1 = f(uOld + dt/2 * rhs0) // rhs2 = f(uOld + dt/2 * rhs1) // rhs3 = f(uOld + dt * rhs2) // rhsSum = rhs0 + 2 * rhs1 + 2 * rhs2 + rhs3 // uNew = uOld + dt/6 * rhsSum // // A lot of code is repeatedly inlined for better efficiency. { // Compute intermediate steps and weighted rhs sum { let dxdt let dydt let dzdt let dwdt // RK4 intermediate step 0 { // Load the current point aka `uOld`. let x := mload(point) let y := mload(add(point, 0x20)) let z := mload(add(point, 0x40)) let w := mload(add(point, 0x60)) // Compute the rhs for the current intermediate step // x' = a (y - x) dxdt := sar(PRECISION, mul(ALPHA, sub(y, x))) // y' = w + x z dydt := add(w, sar(PRECISION, mul(x, z))) // z' = b - x y dzdt := sub(BETA, sar(PRECISION, mul(x, y))) // w' = y z - c w dwdt := sar( PRECISION, sub(mul(y, z), mul(GAMMA, w)) ) // Initialise the `rhsSum` with the current `rhs0` mstore(rhsSum, dxdt) mstore(add(rhsSum, 0x20), dydt) mstore(add(rhsSum, 0x40), dzdt) mstore(add(rhsSum, 0x60), dwdt) // Since the rhs f(uOld) will be used to compute a // tangent later, we'll store it here to prevent // an unnecessay recompuation. mstore(tangent, dxdt) mstore(add(tangent, 0x20), dydt) mstore(add(tangent, 0x40), dzdt) mstore(add(tangent, 0x60), dwdt) } // RK4 intermediate step 1 { // Load the current point aka `uOld`. let x := mload(point) let y := mload(add(point, 0x20)) let z := mload(add(point, 0x40)) let w := mload(add(point, 0x60)) // Compute the current intermediate state. // Precision + 1 for dt / 2 x := add(x, sar(PRECISION_PLUS_1, mul(dxdt, dt))) y := add(y, sar(PRECISION_PLUS_1, mul(dydt, dt))) z := add(z, sar(PRECISION_PLUS_1, mul(dzdt, dt))) w := add(w, sar(PRECISION_PLUS_1, mul(dwdt, dt))) // Compute the rhs for the current intermediate step // x' = a (y - x) dxdt := sar(PRECISION, mul(ALPHA, sub(y, x))) // y' = w + x z dydt := add(w, sar(PRECISION, mul(x, z))) // z' = b - x y dzdt := sub(BETA, sar(PRECISION, mul(x, y))) // w' = y z - c w dwdt := sar( PRECISION, sub(mul(y, z), mul(GAMMA, w)) ) // Add `rhs1` to the `rhsSum`. // shl for adding it twice. mstore(rhsSum, add(mload(rhsSum), shl(1, dxdt))) mstore( add(rhsSum, 0x20), add(mload(add(rhsSum, 0x20)), shl(1, dydt)) ) mstore( add(rhsSum, 0x40), add(mload(add(rhsSum, 0x40)), shl(1, dzdt)) ) mstore( add(rhsSum, 0x60), add(mload(add(rhsSum, 0x60)), shl(1, dwdt)) ) } // RK4 intermediate step 2 { // Load the current point aka `uOld`. let x := mload(point) let y := mload(add(point, 0x20)) let z := mload(add(point, 0x40)) let w := mload(add(point, 0x60)) // Compute the current intermediate state. // Precision + 1 for dt / 2 x := add(x, sar(PRECISION_PLUS_1, mul(dxdt, dt))) y := add(y, sar(PRECISION_PLUS_1, mul(dydt, dt))) z := add(z, sar(PRECISION_PLUS_1, mul(dzdt, dt))) w := add(w, sar(PRECISION_PLUS_1, mul(dwdt, dt))) // Compute the rhs for the current intermediate step // x' = a (y - x) dxdt := sar(PRECISION, mul(ALPHA, sub(y, x))) // y' = w + x z dydt := add(w, sar(PRECISION, mul(x, z))) // z' = b - x y dzdt := sub(BETA, sar(PRECISION, mul(x, y))) // w' = y z - c w dwdt := sar( PRECISION, sub(mul(y, z), mul(GAMMA, w)) ) // Add `rhs2` to the `rhsSum`. // shl for adding it twice. mstore(rhsSum, add(mload(rhsSum), shl(1, dxdt))) mstore( add(rhsSum, 0x20), add(mload(add(rhsSum, 0x20)), shl(1, dydt)) ) mstore( add(rhsSum, 0x40), add(mload(add(rhsSum, 0x40)), shl(1, dzdt)) ) mstore( add(rhsSum, 0x60), add(mload(add(rhsSum, 0x60)), shl(1, dwdt)) ) } // RK4 intermediate step 3 { // Load the current point aka `uOld`. let x := mload(point) let y := mload(add(point, 0x20)) let z := mload(add(point, 0x40)) let w := mload(add(point, 0x60)) // Compute the current intermediate state. x := add(x, sar(PRECISION, mul(dxdt, dt))) y := add(y, sar(PRECISION, mul(dydt, dt))) z := add(z, sar(PRECISION, mul(dzdt, dt))) w := add(w, sar(PRECISION, mul(dwdt, dt))) // Compute the rhs for the current intermediate step // x' = a (y - x) dxdt := sar(PRECISION, mul(ALPHA, sub(y, x))) // y' = w + x z dydt := add(w, sar(PRECISION, mul(x, z))) // z' = b - x y dzdt := sub(BETA, sar(PRECISION, mul(x, y))) // w' = y z - c w dwdt := sar( PRECISION, sub(mul(y, z), mul(GAMMA, w)) ) // Add `rhs3` to the `rhsSum`. mstore(rhsSum, add(mload(rhsSum), dxdt)) mstore( add(rhsSum, 0x20), add(mload(add(rhsSum, 0x20)), dydt) ) mstore( add(rhsSum, 0x40), add(mload(add(rhsSum, 0x40)), dzdt) ) mstore( add(rhsSum, 0x60), add(mload(add(rhsSum, 0x60)), dwdt) ) } } // Compute the new point aka `uNew`. { // Unfortunately, we cannot pull this outside the loop // because tthe stack will be too deep. let dtSixth := div(dt, 6) // Load the current point aka `uOld`. let x := mload(point) let y := mload(add(point, 0x20)) let z := mload(add(point, 0x40)) let w := mload(add(point, 0x60)) // Compute `uNew = dt/6 * rhsSum` x := add(x, sar(PRECISION, mul(mload(rhsSum), dtSixth))) y := add( y, sar( PRECISION, mul(mload(add(rhsSum, 0x20)), dtSixth) ) ) z := add( z, sar( PRECISION, mul(mload(add(rhsSum, 0x40)), dtSixth) ) ) w := add( w, sar( PRECISION, mul(mload(add(rhsSum, 0x60)), dtSixth) ) ) // Update the point / state of the system. mstore(point, x) mstore(add(point, 0x20), y) mstore(add(point, 0x40), z) mstore(add(point, 0x60), w) } } // Check if we are at a step where we have to store the point // to the results. if eq(addmod(iter, 1, skip), 0) { // If so, project and store the 2D data let x := projectPointX(point, projectionParameters) let y := projectPointY(point, projectionParameters) posPoints := storeData(posPoints, x, y) } // Check if we are at a step where we have to store the tangent // to the results. This is not the same as for points since // tangents corresponds to `f(uOld)`. The two are seperated by // one iteration. if eq(mod(iter, skip), 0) { // Tangent will be used by renders to generate cubic Bezier // curves. Following the rhs by `dtTangent = skip * dt / 3` // yields optimal results for this. let dtTangent := div(mul(skip, dt), 3) let x := sar( PRECISION, mul( dtTangent, projectDirectionX(tangent, projectionParameters) ) ) let y := sar( PRECISION, mul( dtTangent, projectDirectionY(tangent, projectionParameters) ) ) posTangents := storeData(posTangents, x, y) } } // Using a `skip` that divides `numberOfIterations` without rest // results in tangents being one entry short at the end. // Let's compute and add this one manually. if eq(mod(numberOfIterations, skip), 0) { { let dxdt let dydt let dzdt let dwdt // Compute the tangent aka in analogy to the in the 0th // intermediate step of the RK4 scheme // I am sure you know the drill by now. { let x := mload(point) let y := mload(add(point, 0x20)) let z := mload(add(point, 0x40)) let w := mload(add(point, 0x60)) // x' = a (y - x) dxdt := sar(PRECISION, mul(ALPHA, sub(y, x))) // y' = w + x z dydt := add(w, sar(PRECISION, mul(x, z))) // z' = b - x y dzdt := sub(BETA, sar(PRECISION, mul(x, y))) // w' = y z - c w dwdt := sar(PRECISION, sub(mul(y, z), mul(GAMMA, w))) // x' = sigma * (y - x) mstore(tangent, dxdt) mstore(add(tangent, 0x20), dydt) mstore(add(tangent, 0x40), dzdt) mstore(add(tangent, 0x60), dwdt) } // Project and store the tangent. Same as at the end of the // main loop, see above. { let dtTangent := div(mul(skip, dt), 3) let x := sar( PRECISION, mul( dtTangent, projectDirectionX(tangent, projectionParameters) ) ) let y := sar( PRECISION, mul( dtTangent, projectDirectionY(tangent, projectionParameters) ) ) posTangents := storeData(posTangents, x, y) } } } } } } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 David Huber (@cxkoda) // All Rights Reserved pragma solidity >=0.8.0 <0.9.0; import "./AttractorSolver.sol"; import "../utils/MathHelpers.sol"; /** * @notice Base class for four-dimensional attractor simulators. * @dev Partial specialisation of `AttractorSolver` for four-dimensional * systems. * @author David Huber (@cxkoda) */ abstract contract AttractorSolver4D is AttractorSolver { uint8 internal constant DIM = 4; /** * @notice Four-dimensional starting point (see `StartingPoint`). * @dev This type will be used internally for the 3D solvers. */ struct StartingPoint4D { int256[DIM] startingPoint; } /** * @notice Four-dimensional projection parameters point (see * `ProjectionParameters`). * @dev This type will be used internally for the 3D solvers. */ struct ProjectionParameters4D { int256[DIM] axis1; int256[DIM] axis2; int256[DIM] offset; } /** * @notice See `IAttractorSolver.getDimensionality`. */ function getDimensionality() public pure virtual override returns (uint8) { return DIM; } /** * @notice Converts dynamic to static arrays. * @dev Converts only arrays with length `DIM` */ function _convertDynamicToStaticArray(int256[] memory input) internal pure returns (int256[DIM] memory output) { require(input.length == DIM); for (uint256 dim = 0; dim < DIM; ++dim) { output[dim] = input[dim]; } } /** * @notice Converts dynamic to static arrays. * @dev Only applicable to arrays with length `DIM` */ function _parseStartingPoint(StartingPoint memory startingPoint_) internal pure returns (StartingPoint4D memory startingPoint) { startingPoint.startingPoint = _convertDynamicToStaticArray( startingPoint_.startingPoint ); } /** * @dev Converts dynamical length projections parameters to static ones * for internal use. */ function _parseProjectionParameters( ProjectionParameters memory projectionParameters_ ) internal pure returns (ProjectionParameters4D memory projectionParameters) { require(isValidProjectionParameters(projectionParameters_)); projectionParameters.axis1 = _convertDynamicToStaticArray( projectionParameters_.axis1 ); projectionParameters.axis2 = _convertDynamicToStaticArray( projectionParameters_.axis2 ); projectionParameters.offset = _convertDynamicToStaticArray( projectionParameters_.offset ); } /** * @notice See `IAttractorSolver.getDefaultProjectionParameters`. * @dev The implementation relies on spherical Fibonacci lattices from * `MathHelpers` to compute the direction of the axes. Their normalisation * and offset is delegated to specialisations of `_getDefaultProjectionScale` * and `_getDefaultProjectionOffset` depending on the system. */ function getDefaultProjectionParameters(uint256 editionId) external view virtual override returns (ProjectionParameters memory projectionParameters) { projectionParameters.offset = _getDefaultProjectionOffset(); projectionParameters.axis1 = new int256[](DIM); projectionParameters.axis2 = new int256[](DIM); // Make some chaos uint256 fiboIdx = ((editionId / 4) * 7 + 13) % 32; (int256[3] memory axis1, int256[3] memory axis2) = MathHelpers .getFibonacciSphericalAxes(fiboIdx, 32); int256 scale = _getDefaultProjectionScale(); // Apply length and store back for (uint8 dim; dim < 3; dim++) { uint256 coord = dim + editionId; projectionParameters.axis1[coord % DIM] = (scale * axis1[dim])/ONE; projectionParameters.axis2[coord % DIM] = (scale * axis2[dim])/ONE; } } /** * @notice See `IAttractorSolver.computeSolution`. */ function computeSolution( SolverParameters calldata solverParameters, StartingPoint calldata startingPoint, ProjectionParameters calldata projectionParameters ) external pure override onlyValidProjectionParameters(projectionParameters) returns (AttractorSolution memory solution) { // Delegate and repack the solution (solution.points, solution.tangents) = _solve( solverParameters, _parseStartingPoint(startingPoint), _parseProjectionParameters(projectionParameters) ); // Compute the timestep between points in the output considering that // not all simulated points will be stored. solution.dt = solverParameters.dt * solverParameters.skip; } /** * @dev The simulaton routine to be implemented for the individual systems. * This intermediate interface was introduced to make variables more * easility accessibly in assembly code. */ function _solve( SolverParameters memory solverParameters, StartingPoint4D memory startingPoint, ProjectionParameters4D memory projectionParameters ) internal pure virtual returns (bytes memory points, bytes memory tangents); /** * @dev Retuns the default length of the projection axes for the * respective system. * Attention: Here we use integers instead of fixed-point numbers for * simplicity. */ function _getDefaultProjectionScale() internal pure virtual returns (int256); /** * @dev Returns the default offset of the projection for the respective * system. */ function _getDefaultProjectionOffset() internal pure virtual returns (int256[] memory); } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 David Huber (@cxkoda) // All Rights Reserved pragma solidity >=0.8.0 <0.9.0; import "./IAttractorSolver.sol"; /** * @notice Base class for attractor simulators. * @dev The contract implements some convenient routines shared across * different AttractorSolvers. * @author David Huber (@cxkoda) */ abstract contract AttractorSolver is IAttractorSolver { /** * @notice The fixed-number precision used throughout this project. */ uint8 public constant PRECISION = 96; uint8 internal constant PRECISION_PLUS_1 = 97; int256 internal constant ONE = 2**96; /** * @dev The simulation results (see `AttractorSolution`) will be stored as * 16-bit fixed-point values with precision 6. This implies a right shift * of internally used (higher-precision) values by 96-6=90. * Reducing the width to 16-bit at a precision of 6 futher means that the * left 256-96-10=150 bits of the original (256 bit) number will be dropped. */ uint256 internal constant PRECISION_REDUCTION_SAR = 90; uint256 internal constant RANGE_REDUCTION_SHL = 150; /** * @notice See `IAttractorSolver.getFixedPointPrecision`. */ function getFixedPointPrecision() external pure override returns (uint8) { return PRECISION; } /** * @notice See `IAttractorSolver.isValidProjectionParameters` * @dev Performs a simple dimensionality check. */ function isValidProjectionParameters( ProjectionParameters memory projectionParameters ) public pure override returns (bool) { return (projectionParameters.axis1.length == getDimensionality()) && (projectionParameters.axis2.length == getDimensionality()) && (projectionParameters.offset.length == getDimensionality()); } /** * @dev Modifier checking for `isValidProjectionParameters`. */ modifier onlyValidProjectionParameters( ProjectionParameters memory projectionParameters ) { require( isValidProjectionParameters(projectionParameters), "Invalid Projection Parameters" ); _; } /** * @notice Compute a random number in a given `range` around zero. * @dev Computes deterministic PRNs based on a given input `seed`. The * values are distributed quasi-equally in the interval `[-range, range]`. * @return newSeed To be used in the next function call. */ function _random(uint256 seed, int256 range) internal pure returns (uint256 newSeed, int256 randomNumber) { newSeed = uint256(keccak256(abi.encode(seed))); randomNumber = int256(newSeed); assembly { randomNumber := sub(mod(newSeed, shl(1, range)), range) } } /** * @notice See `IAttractorSolver.getDimensionality`. */ function getDimensionality() public pure virtual override returns (uint8); } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 David Huber (@cxkoda) // All Rights Reserved pragma solidity >=0.8.0 <0.9.0; /** * @notice A point on the sphere with unit radius. * @dev Since we will be interested in 3D points in the end, it makes more * sense to just store trigonimetric values (and don't spend the effort * to invert to the actual angles). */ struct SphericalPoint { int256 sinAzimuth; int256 cosAzimuth; int256 sinAltitude; int256 cosAltitude; } /** * @notice Some special math functions used for `Strange Attractors`. * @dev The functions use fixed-point number with the same precision (96) as * the numerical solvers (see also `IAttractorSolver`). * @author David Huber (@cxkoda) */ library MathHelpers { uint8 public constant PRECISION = 96; /** * @dev Some handy constants. */ int256 private constant ONE = 2**96; int256 public constant PI = 248902613312231085230521944622; int256 public constant PI_2 = 497805226624462170461043889244; int256 public constant MINUS_PI_2 = -497805226624462170461043889244; int256 public constant PI_0_5 = 124451306656115542615260972311; /** * @notice Taylor series coefficients for sin around 0. */ int256 private constant COEFFICIENTS_SIN_1 = 2**96; int256 private constant COEFFICIENTS_SIN_3 = -(2**96 + 2) / 6; int256 private constant COEFFICIENTS_SIN_5 = (2**96 - 16) / 120; int256 private constant COEFFICIENTS_SIN_7 = -(2**96 + 944) / 5040; int256 private constant COEFFICIENTS_SIN_9 = (2**96 - 205696) / 362880; int256 private constant COEFFICIENTS_SIN_11 = -(2**96 + 34993664) / 39916800; /** * @notice A pure solidity approximation of the sine function. * @dev The implementation uses a broken Taylor series approximation to * compute values. The absolute error is <1e-3. */ function sin(int256 x) public pure returns (int256 result) { assembly { // We remap the x to the range [-pi, pi] first, since the Taylor // series is most accurate there. // Attention: smod(-10, 2) = -10 but smod(-10, -2) = 0 // We therefore shift the numbers to the positive side first x := add(smod(x, MINUS_PI_2), PI_2) // Restrict to the range [-pi, pi] x := sub(addmod(x, PI, PI_2), PI) let x2 := sar(PRECISION, mul(x, x)) result := sar( PRECISION, mul( x, add( COEFFICIENTS_SIN_1, sar( PRECISION, mul( x2, add( COEFFICIENTS_SIN_3, sar( PRECISION, mul( x2, add( COEFFICIENTS_SIN_5, sar( PRECISION, mul( x2, add( COEFFICIENTS_SIN_7, sar( PRECISION, mul( x2, add( COEFFICIENTS_SIN_9, sar( PRECISION, mul( x2, COEFFICIENTS_SIN_11 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) } } /** * @notice Taylor series coefficients for cos around 0. */ int256 private constant COEFFICIENTS_COS_2 = -(2**96 / 2); int256 private constant COEFFICIENTS_COS_4 = (2**96 - 16) / 24; int256 private constant COEFFICIENTS_COS_6 = -(2**96 + 224) / 720; int256 private constant COEFFICIENTS_COS_8 = (2**96 - 4096) / 40320; int256 private constant COEFFICIENTS_COS_10 = -(2**96 + 2334464) / 3628800; int256 private constant COEFFICIENTS_COS_12 = (2**96 - 204507136) / 479001600; /** * @notice A pure solidity approximation of the cosine function. * @dev The implementation uses a broken Taylor series approximation to * compute values. The absolute error is <1e-3. */ function cos(int256 x) public pure returns (int256 result) { assembly { // We remap the x to the range [-pi, pi] first, since the Taylor // series is most accurate there. // Attention: smod(-10, 2) = -10 but smod(-10, -2) = 0 // We therefore shift the numbers to the positive side first x := add(smod(x, MINUS_PI_2), PI_2) // Restrict to the range [-pi, pi] x := sub(addmod(x, PI, PI_2), PI) let x2 := sar(PRECISION, mul(x, x)) result := add( ONE, sar( PRECISION, mul( x2, add( COEFFICIENTS_COS_2, sar( PRECISION, mul( x2, add( COEFFICIENTS_COS_4, sar( PRECISION, mul( x2, add( COEFFICIENTS_COS_6, sar( PRECISION, mul( x2, add( COEFFICIENTS_COS_8, sar( PRECISION, mul( x2, add( COEFFICIENTS_COS_10, sar( PRECISION, mul( x2, COEFFICIENTS_COS_12 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) } } /** * @notice A pure solidity approximation of the square root function. * @dev The implementation uses the Babylonian method with a fixed amount of * steps (for a predictable gas). The approximation is optimised for values * in the range of[0,1]. The absolute error is <1e-3. */ function sqrt(int256 x) public pure returns (int256 result) { require(x >= 0, "Sqrt is only defined for positive numbers"); assembly { result := x result := sar(1, add(div(shl(PRECISION, x), result), result)) result := sar(1, add(div(shl(PRECISION, x), result), result)) result := sar(1, add(div(shl(PRECISION, x), result), result)) result := sar(1, add(div(shl(PRECISION, x), result), result)) result := sar(1, add(div(shl(PRECISION, x), result), result)) result := sar(1, add(div(shl(PRECISION, x), result), result)) result := sar(1, add(div(shl(PRECISION, x), result), result)) } } int256 private constant GOLDEN_RATIO = 128193859814280023944822833248; /** * @notice Computes quasi-equidistant points on a unit-sphere. * @dev The function employs Fibonacci lattices remapped to the unit-sphere * to compute `numPoints` different points in spherical coordinates. It * should be noted that we use the angle convention `altitude`(=theta) in * [-pi/2, pi/2]. */ function getFibonacciLatticeOnSphere(uint256 idx, uint256 numPoints) internal pure returns (SphericalPoint memory sphericalPoint) { require(idx >= 0 && idx < numPoints, "Index out of range"); sphericalPoint.sinAltitude = (2 * ONE * int256(idx)) / int256(numPoints) - ONE; { int256 sinAltitude2 = sphericalPoint.sinAltitude; assembly { sinAltitude2 := sar(PRECISION, mul(sinAltitude2, sinAltitude2)) } sphericalPoint.cosAltitude = sqrt(ONE - sinAltitude2); } { int256 azimuth; assembly { azimuth := smod( div(shl(PRECISION, mul(PI_2, idx)), GOLDEN_RATIO), PI_2 ) } sphericalPoint.cosAzimuth = cos(azimuth); sphericalPoint.sinAzimuth = sin(azimuth); } } /** * @notice Computes projection axes for different directions. * @dev Uses the directions provided by `getFibonacciLatticeOnSphere` to * compute two normalised, orthogonal axes. The are computed by rotating the * x-z projection plane first by `altitude` around -x and then by `azimuth` * around +z. */ function getFibonacciSphericalAxes(uint256 idx, uint256 numPoints) external pure returns (int256[3] memory axis1, int256[3] memory axis2) { SphericalPoint memory sphericalPoint = getFibonacciLatticeOnSphere( idx, numPoints ); axis1 = [sphericalPoint.cosAzimuth, sphericalPoint.sinAzimuth, 0]; axis2 = [ -sphericalPoint.sinAzimuth * sphericalPoint.sinAltitude, sphericalPoint.cosAzimuth * sphericalPoint.sinAltitude, sphericalPoint.cosAltitude ]; assembly { let pos := axis2 mstore(pos, sar(PRECISION, mload(pos))) pos := add(pos, 0x20) mstore(pos, sar(PRECISION, mload(pos))) } } } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 David Huber (@cxkoda) // All Rights Reserved pragma solidity >=0.8.0 <0.9.0; import "./AttractorSolution.sol"; /** * @notice Parameters going to the numerical ODE solver. * @param numberOfIterations Total number of iterations. * @param dt Timestep increment in each iteration * @param skip Amount of iterations between storing two points. * @dev `numberOfIterations` has to be dividable without rest by `skip`. */ struct SolverParameters { uint256 numberOfIterations; uint256 dt; uint8 skip; } /** * @notice Parameters going to the projection routines. * @dev The lengths of all fields have to match the dimensionality of the * considered system. * @param axis1 First projection axis (horizontal image coordinate) * @param axis2 Second projection axis (vertical image coordinate) * @param offset Offset applied before projecting. */ struct ProjectionParameters { int256[] axis1; int256[] axis2; int256[] offset; } /** * @notice Starting point for the numerical simulation * @dev The length of the starting point has to match the dimensionality of the * considered system. * I agree, this struct looks kinda dumb, but I really like speaking types. * So as long as we don't have typedefs for non-elementary types, we are stuck * with this cruelty. */ struct StartingPoint { int256[] startingPoint; } /** * @notice Interface for simulators of chaotic systems. * @dev Implementations of this interface will contain the mathematical * description of the underlying differential equations, deal with its numerical * solution and the 2D projection of the results. * Implementations will internally use fixed-point numbers with a precision of * 96 bits by convention. * @author David Huber (@cxkoda) */ interface IAttractorSolver { /** * @notice Simulates the evolution of a chaotic system. * @dev This is the core piece of this class that performs everything * at once. All relevant algorithm for the evaluation of the ODEs * the numerical scheme, the projection and storage are contained within * this method for performance reasons. * @return An `AttractorSolution` containing already projected 2D points * and tangents to them. */ function computeSolution( SolverParameters calldata, StartingPoint calldata, ProjectionParameters calldata ) external pure returns (AttractorSolution memory); /** * @notice Generates a random starting point for the system. */ function getRandomStartingPoint(uint256 randomSeed) external view returns (StartingPoint memory); /** * @notice Generates the default projection for a given edition of the * system. */ function getDefaultProjectionParameters(uint256 editionId) external view returns (ProjectionParameters memory); /** * @notice Returns the type/name of the dynamical system. */ function getSystemType() external pure returns (string memory); /** * @notice Returns the dimensionality of the dynamical system (number of * ODEs). */ function getDimensionality() external pure returns (uint8); /** * @notice Returns the precision of the internally used fixed-point numbers. * @dev The solvers operate on fixed-point numbers with a given PRECISION, * i.e. the amount of bits reserved for decimal places. * By convention, this method will return 96 throughout the project. */ function getFixedPointPrecision() external pure returns (uint8); /** * @notice Checks if given `ProjectionParameters` are valid` */ function isValidProjectionParameters(ProjectionParameters memory) external pure returns (bool); } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 David Huber (@cxkoda) // All Rights Reserved pragma solidity >=0.8.0 <0.9.0; /** * @notice The data struct that will be passed from the solver to the renderer. * @dev `points` and `tangents` both contain pairs of 16-bit fixed-point numbers * with a PRECISION of 6 in row-major order.`dt` is given in the fixed-point * respresentation used by the solvers and corresponds to the time step between * the datapoints. */ struct AttractorSolution { bytes points; bytes tangents; uint256 dt; }
See `IAttractorSolver.getSystemType`./
function getSystemType() public pure override returns (string memory) { return "Huang Multi-Wing"; }
14,541,838
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; // (Uni|Pancake)Swap libs are interchangeable import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol"; import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; /* For lines that are marked ERC20 Token Standard, learn more at https://eips.ethereum.org/EIPS/eip-20. */ contract ERC20Deflationary is Context, IERC20, Ownable { // Keeps track of balances for address that are included in receiving reward. mapping (address => uint256) private _reflectionBalances; // Keeps track of balances for address that are excluded from receiving reward. mapping (address => uint256) private _tokenBalances; // Keeps track of which address are excluded from fee. mapping (address => bool) private _isExcludedFromFee; // Keeps track of which address are excluded from reward. mapping (address => bool) private _isExcludedFromReward; // An array of addresses that are excluded from reward. address[] private _excludedFromReward; // ERC20 Token Standard mapping (address => mapping (address => uint256)) private _allowances; // Liquidity pool provider router IUniswapV2Router02 internal _uniswapV2Router; // This Token and WETH pair contract address. address internal _uniswapV2Pair; // Where burnt tokens are sent to. This is an address that no one can have accesses to. address private constant burnAccount = 0x000000000000000000000000000000000000dEaD; /* Tax rate = (_taxXXX / 10**_tax_XXXDecimals) percent. For example: if _taxBurn is 1 and _taxBurnDecimals is 2. Tax rate = 0.01% If you want tax rate for burn to be 5% for example, set _taxBurn to 5 and _taxBurnDecimals to 0. 5 * (10 ** 0) = 5 */ // Decimals of taxBurn. Used for have tax less than 1%. uint8 private _taxBurnDecimals; // Decimals of taxReward. Used for have tax less than 1%. uint8 private _taxRewardDecimals; // Decimals of taxLiquify. Used for have tax less than 1%. uint8 private _taxLiquifyDecimals; // This percent of a transaction will be burnt. uint8 private _taxBurn; // This percent of a transaction will be redistribute to all holders. uint8 private _taxReward; // This percent of a transaction will be added to the liquidity pool. More details at https://github.com/Sheldenshi/ERC20Deflationary. uint8 private _taxLiquify; // ERC20 Token Standard uint8 private _decimals; // ERC20 Token Standard uint256 private _totalSupply; // Current supply:= total supply - burnt tokens uint256 private _currentSupply; // A number that helps distributing fees to all holders respectively. uint256 private _reflectionTotal; // Total amount of tokens rewarded / distributing. uint256 private _totalRewarded; // Total amount of tokens burnt. uint256 private _totalBurnt; // Total amount of tokens locked in the LP (this token and WETH pair). uint256 private _totalTokensLockedInLiquidity; // Total amount of ETH locked in the LP (this token and WETH pair). uint256 private _totalETHLockedInLiquidity; // A threshold for swap and liquify. uint256 private _minTokensBeforeSwap; // ERC20 Token Standard string private _name; // ERC20 Token Standard string private _symbol; // Whether a previous call of SwapAndLiquify process is still in process. bool private _inSwapAndLiquify; bool private _autoSwapAndLiquifyEnabled; bool private _autoBurnEnabled; bool private _rewardEnabled; // Prevent reentrancy. modifier lockTheSwap { require(!_inSwapAndLiquify, "Currently in swap and liquify."); _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } // Return values of _getValues function. struct ValuesFromAmount { // Amount of tokens for to transfer. uint256 amount; // Amount tokens charged for burning. uint256 tBurnFee; // Amount tokens charged to reward. uint256 tRewardFee; // Amount tokens charged to add to liquidity. uint256 tLiquifyFee; // Amount tokens after fees. uint256 tTransferAmount; // Reflection of amount. uint256 rAmount; // Reflection of burn fee. uint256 rBurnFee; // Reflection of reward fee. uint256 rRewardFee; // Reflection of liquify fee. uint256 rLiquifyFee; // Reflection of transfer amount. uint256 rTransferAmount; } /* Events */ event Burn(address from, uint256 amount); event TaxBurnUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxRewardUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event TaxLiquifyUpdate(uint8 previousTax, uint8 previousDecimals, uint8 currentTax, uint8 currentDecimal); event MinTokensBeforeSwapUpdated(uint256 previous, uint256 current); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensAddedToLiquidity ); event ExcludeAccountFromReward(address account); event IncludeAccountInReward(address account); event ExcludeAccountFromFee(address account); event IncludeAccountInFee(address account); event EnabledAutoBurn(); event EnabledReward(); event EnabledAutoSwapAndLiquify(); event DisabledAutoBurn(); event DisabledReward(); event DisabledAutoSwapAndLiquify(); event Airdrop(uint256 amount); constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 tokenSupply_) { // Sets the values for `name`, `symbol`, `totalSupply`, `currentSupply`, and `rTotal`. _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = tokenSupply_ * (10 ** decimals_); _currentSupply = _totalSupply; _reflectionTotal = (~uint256(0) - (~uint256(0) % _totalSupply)); // Mint _reflectionBalances[_msgSender()] = _reflectionTotal; // exclude owner and this contract from fee. excludeAccountFromFee(owner()); excludeAccountFromFee(address(this)); // exclude owner, burnAccount, and this contract from receiving rewards. _excludeAccountFromReward(owner()); _excludeAccountFromReward(burnAccount); _excludeAccountFromReward(address(this)); emit Transfer(address(0), _msgSender(), _totalSupply); } // allow the contract to receive ETH receive() external payable {} /** * @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`). * * 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 Returns the address of this token and WETH pair. */ function uniswapV2Pair() public view virtual returns (address) { return _uniswapV2Pair; } /** * @dev Returns the current burn tax. */ function taxBurn() public view virtual returns (uint8) { return _taxBurn; } /** * @dev Returns the current reward tax. */ function taxReward() public view virtual returns (uint8) { return _taxReward; } /** * @dev Returns the current liquify tax. */ function taxLiquify() public view virtual returns (uint8) { return _taxLiquify; } /** * @dev Returns the current burn tax decimals. */ function taxBurnDecimals() public view virtual returns (uint8) { return _taxBurnDecimals; } /** * @dev Returns the current reward tax decimals. */ function taxRewardDecimals() public view virtual returns (uint8) { return _taxRewardDecimals; } /** * @dev Returns the current liquify tax decimals. */ function taxLiquifyDecimals() public view virtual returns (uint8) { return _taxLiquifyDecimals; } /** * @dev Returns true if auto burn feature is enabled. */ function autoBurnEnabled() public view virtual returns (bool) { return _autoBurnEnabled; } /** * @dev Returns true if reward feature is enabled. */ function rewardEnabled() public view virtual returns (bool) { return _rewardEnabled; } /** * @dev Returns true if auto swap and liquify feature is enabled. */ function autoSwapAndLiquifyEnabled() public view virtual returns (bool) { return _autoSwapAndLiquifyEnabled; } /** * @dev Returns the threshold before swap and liquify. */ function minTokensBeforeSwap() external view virtual returns (uint256) { return _minTokensBeforeSwap; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns current supply of the token. * (currentSupply := totalSupply - totalBurnt) */ function currentSupply() external view virtual returns (uint256) { return _currentSupply; } /** * @dev Returns the total number of tokens burnt. */ function totalBurnt() external view virtual returns (uint256) { return _totalBurnt; } /** * @dev Returns the total number of tokens locked in the LP. */ function totalTokensLockedInLiquidity() external view virtual returns (uint256) { return _totalTokensLockedInLiquidity; } /** * @dev Returns the total number of ETH locked in the LP. */ function totalETHLockedInLiquidity() external view virtual returns (uint256) { return _totalETHLockedInLiquidity; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { if (_isExcludedFromReward[account]) return _tokenBalances[account]; return tokenFromReflection(_reflectionBalances[account]); } /** * @dev Returns whether an account is excluded from reward. */ function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedFromReward[account]; } /** * @dev Returns whether an account is excluded from fee. */ function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[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); require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _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 virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Burn} event indicating the amount burnt. * Emits a {Transfer} event with `to` set to the burn 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 != burnAccount, "ERC20: burn from the burn address"); uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); uint256 rAmount = _getRAmount(amount); // Transfer from account to the burnAccount if (_isExcludedFromReward[account]) { _tokenBalances[account] -= amount; } _reflectionBalances[account] -= rAmount; _tokenBalances[burnAccount] += amount; _reflectionBalances[burnAccount] += rAmount; _currentSupply -= amount; _totalBurnt += amount; emit Burn(account, amount); emit Transfer(account, burnAccount, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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"); ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]); if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferFromExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferToExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferStandard(sender, recipient, values); } else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferBothExcluded(sender, recipient, values); } else { _transferStandard(sender, recipient, values); } emit Transfer(sender, recipient, values.tTransferAmount); if (!_isExcludedFromFee[sender]) { _afterTokenTransfer(values); } } /** * @dev Performs all the functionalities that are enabled. */ function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual { // Burn if (_autoBurnEnabled) { _tokenBalances[address(this)] += values.tBurnFee; _reflectionBalances[address(this)] += values.rBurnFee; _approve(address(this), _msgSender(), values.tBurnFee); burnFrom(address(this), values.tBurnFee); } // Reflect if (_rewardEnabled) { _distributeFee(values.rRewardFee, values.tRewardFee); } // Add to liquidity pool if (_autoSwapAndLiquifyEnabled) { // add liquidity fee to this contract. _tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; uint256 contractBalance = _tokenBalances[address(this)]; // whether the current contract balances makes the threshold to swap and liquify. bool overMinTokensBeforeSwap = contractBalance >= _minTokensBeforeSwap; if (overMinTokensBeforeSwap && !_inSwapAndLiquify && _msgSender() != _uniswapV2Pair && _autoSwapAndLiquifyEnabled ) { swapAndLiquify(contractBalance); } } } /** * @dev Performs transfer between two accounts that are both included in receiving reward. */ function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an included account to an excluded account. * (included and excluded from receiving reward.) */ function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer from an excluded account to an included account. * (included and excluded from receiving reward.) */ function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Performs transfer between two accounts that are both excluded in receiving reward. */ function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; } /** * @dev Destroys `amount` tokens from the caller. * */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } /** * @dev Excludes an account from receiving reward. * * Emits a {ExcludeAccountFromReward} event. * * Requirements: * * - `account` is included in receiving reward. */ function _excludeAccountFromReward(address account) internal { require(!_isExcludedFromReward[account], "Account is already excluded."); if(_reflectionBalances[account] > 0) { _tokenBalances[account] = tokenFromReflection(_reflectionBalances[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); emit ExcludeAccountFromReward(account); } /** * @dev Includes an account from receiving reward. * * Emits a {IncludeAccountInReward} event. * * Requirements: * * - `account` is excluded in receiving reward. */ function _includeAccountInReward(address account) internal { require(_isExcludedFromReward[account], "Account is already included."); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tokenBalances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } emit IncludeAccountInReward(account); } /** * @dev Excludes an account from fee. * * Emits a {ExcludeAccountFromFee} event. * * Requirements: * * - `account` is included in fee. */ function excludeAccountFromFee(address account) internal { require(!_isExcludedFromFee[account], "Account is already excluded."); _isExcludedFromFee[account] = true; emit ExcludeAccountFromFee(account); } /** * @dev Includes an account from fee. * * Emits a {IncludeAccountFromFee} event. * * Requirements: * * - `account` is excluded in fee. */ function includeAccountInFee(address account) internal { require(_isExcludedFromFee[account], "Account is already included."); _isExcludedFromFee[account] = false; emit IncludeAccountInFee(account); } /** * @dev Airdrop tokens to all holders that are included from reward. * Requirements: * - the caller must have a balance of at least `amount`. */ function airdrop(uint256 amount) public { address sender = _msgSender(); //require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); require(balanceOf(sender) >= amount, "The caller must have balance >= amount."); ValuesFromAmount memory values = _getValues(amount, false); if (_isExcludedFromReward[sender]) { _tokenBalances[sender] -= values.amount; } _reflectionBalances[sender] -= values.rAmount; _reflectionTotal = _reflectionTotal - values.rAmount; _totalRewarded += amount ; emit Airdrop(amount); } /** * @dev Returns the reflected amount of a token. * Requirements: * - `amount` must be less than total supply. */ function reflectionFromToken(uint256 amount, bool deductTransferFee) internal view returns(uint256) { require(amount <= _totalSupply, "Amount must be less than supply"); ValuesFromAmount memory values = _getValues(amount, deductTransferFee); return values.rTransferAmount; } /** * @dev Used to figure out the balance after reflection. * Requirements: * - `rAmount` must be less than reflectTotal. */ function tokenFromReflection(uint256 rAmount) internal view returns(uint256) { require(rAmount <= _reflectionTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } /** * @dev Swap half of contract's token balance for ETH, * and pair it up with the other half to add to the * liquidity pool. * * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth, * the amount of ETH added to the LP, and the amount of tokens added to the LP. */ function swapAndLiquify(uint256 contractBalance) private lockTheSwap { // Split the contract balance into two halves. uint256 tokensToSwap = contractBalance / 2; uint256 tokensAddToLiquidity = contractBalance - tokensToSwap; // Contract's current ETH balance. uint256 initialBalance = address(this).balance; // Swap half of the tokens to ETH. swapTokensForEth(tokensToSwap); // Figure out the exact amount of tokens received from swapping. uint256 ethAddToLiquify = address(this).balance - initialBalance; // Add to the LP of this token and WETH pair (half ETH and half this token). addLiquidity(ethAddToLiquify, tokensAddToLiquidity); _totalETHLockedInLiquidity += address(this).balance - initialBalance; _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this)); emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity); } /** * @dev Swap `amount` tokens for ETH. * * Emits {Transfer} event. From this contract to the token and WETH Pair. */ function swapTokensForEth(uint256 amount) 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), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), // this contract will receive the eth that were swapped from the token block.timestamp + 60 * 1000 ); } /** * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP. * Depends on the current rate for the pair between this token and WETH, * `ethAmount` and `tokenAmount` might not match perfectly. * Dust(leftover) ETH or token will be refunded to this contract * (usually very small quantity). * * Emits {Transfer} event. From this contract to the token and WETH Pai. */ function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); } /** * @dev Distribute the `tRewardFee` tokens to all holders that are included in receiving reward. * amount received is based on how many token one owns. */ function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private { // This would decrease rate, thus increase amount reward receive based on one's balance. _reflectionTotal = _reflectionTotal - rRewardFee; _totalRewarded += tRewardFee; } /** * @dev Returns fees and transfer amount in both tokens and reflections. * tXXXX stands for tokenXXXX * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) { ValuesFromAmount memory values; values.amount = amount; _getTValues(values, deductTransferFee); _getRValues(values, deductTransferFee); return values; } /** * @dev Adds fees and transfer amount in tokens to `values`. * tXXXX stands for tokenXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private { if (deductTransferFee) { values.tTransferAmount = values.amount; } else { // calculate fee values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals); values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals); values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals); // amount after fee values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee; } } /** * @dev Adds fees and transfer amount in reflection to `values`. * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */ function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private { uint256 currentRate = _getRate(); values.rAmount = values.amount * currentRate; if (deductTransferFee) { values.rTransferAmount = values.rAmount; } else { values.rAmount = values.amount * currentRate; values.rBurnFee = values.tBurnFee * currentRate; values.rRewardFee = values.tRewardFee * currentRate; values.rLiquifyFee = values.tLiquifyFee * currentRate; values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquifyFee; } } /** * @dev Returns `amount` in reflection. */ function _getRAmount(uint256 amount) private view returns (uint256) { uint256 currentRate = _getRate(); return amount * currentRate; } /** * @dev Returns the current reflection rate. */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } /** * @dev Returns the current reflection supply and token supply. */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _reflectionTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply); rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]]; tSupply = tSupply - _tokenBalances[_excludedFromReward[i]]; } if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply); return (rSupply, tSupply); } /** * @dev Returns fee based on `amount` and `taxRate` */ function _calculateTax(uint256 amount, uint8 tax, uint8 taxDecimals_) private pure returns (uint256) { return amount * tax / (10 ** taxDecimals_) / (10 ** 2); } /* Owner functions */ /** * @dev Enables the auto burn feature. * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled. * * Emits a {EnabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(!_autoBurnEnabled, "Auto burn feature is already enabled."); require(taxBurn_ > 0, "Tax must be greater than 0."); require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _autoBurnEnabled = true; setTaxBurn(taxBurn_, taxBurnDecimals_); emit EnabledAutoBurn(); } /** * @dev Enables the reward feature. * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled. * * Emits a {EnabledReward} event. * * Requirements: * * - reward feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(!_rewardEnabled, "Reward feature is already enabled."); require(taxReward_ > 0, "Tax must be greater than 0."); require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _rewardEnabled = true; setTaxReward(taxReward_, taxRewardDecimals_); emit EnabledReward(); } /** * @dev Enables the auto swap and liquify feature. * Swaps half of transaction amount * `taxLiquify_` amount of tokens * to ETH and pair with the other half of tokens to the LP each transaction when enabled. * * Emits a {EnabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */ function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner { require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled."); require(taxLiquify_ > 0, "Tax must be greater than 0."); require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _minTokensBeforeSwap = minTokensBeforeSwap_; // init Router IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(routerAddress); _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).getPair(address(this), uniswapV2Router.WETH()); if (_uniswapV2Pair == address(0)) { _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); } _uniswapV2Router = uniswapV2Router; // exclude uniswapV2Router from receiving reward. _excludeAccountFromReward(address(uniswapV2Router)); // exclude WETH and this Token Pair from receiving reward. _excludeAccountFromReward(_uniswapV2Pair); // exclude uniswapV2Router from paying fees. excludeAccountFromFee(address(uniswapV2Router)); // exclude WETH and this Token Pair from paying fees. excludeAccountFromFee(_uniswapV2Pair); // enable _autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify(); } /** * @dev Disables the auto burn feature. * * Emits a {DisabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be enabled. */ function disableAutoBurn() public onlyOwner { require(_autoBurnEnabled, "Auto burn feature is already disabled."); setTaxBurn(0, 0); _autoBurnEnabled = false; emit DisabledAutoBurn(); } /** * @dev Disables the reward feature. * * Emits a {DisabledReward} event. * * Requirements: * * - reward feature mush be enabled. */ function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); } /** * @dev Disables the auto swap and liquify feature. * * Emits a {DisabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be enabled. */ function disableAutoSwapAndLiquify() public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already disabled."); setTaxLiquify(0, 0); _autoSwapAndLiquifyEnabled = false; emit DisabledAutoSwapAndLiquify(); } /** * @dev Updates `_minTokensBeforeSwap` * * Emits a {MinTokensBeforeSwap} event. * * Requirements: * * - `minTokensBeforeSwap_` must be less than _currentSupply. */ function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner { require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply."); uint256 previous = _minTokensBeforeSwap; _minTokensBeforeSwap = minTokensBeforeSwap_; emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap); } /** * @dev Updates taxBurn * * Emits a {TaxBurnUpdate} event. * * Requirements: * * - auto burn feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function."); require(taxBurn_ + _taxReward + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxBurn; uint8 previousDecimals = _taxBurnDecimals; _taxBurn = taxBurn_; _taxBurnDecimals = taxBurnDecimals_; emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_); } /** * @dev Updates taxReward * * Emits a {TaxRewardUpdate} event. * * Requirements: * * - reward feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function."); require(_taxBurn + taxReward_ + _taxLiquify < 100, "Tax fee too high."); uint8 previousTax = _taxReward; uint8 previousDecimals = _taxRewardDecimals; _taxReward = taxReward_; _taxBurnDecimals = taxRewardDecimals_; emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_); } /** * @dev Updates taxLiquify * * Emits a {TaxLiquifyUpdate} event. * * Requirements: * * - auto swap and liquify feature must be enabled. * - total tax rate must be less than 100%. */ function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function."); require(_taxBurn + _taxReward + taxLiquify_ < 100, "Tax fee too high."); uint8 previousTax = _taxLiquify; uint8 previousDecimals = _taxLiquifyDecimals; _taxLiquify = taxLiquify_; _taxLiquifyDecimals = taxLiquifyDecimals_; emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_); } }
Disables the auto burn feature. Emits a {DisabledAutoBurn} event. Requirements: - auto burn feature mush be enabled./
function disableAutoBurn() public onlyOwner { require(_autoBurnEnabled, "Auto burn feature is already disabled."); setTaxBurn(0, 0); _autoBurnEnabled = false; emit DisabledAutoBurn(); }
916,840
./full_match/1/0x1d9619E10086FdC1065B114298384aAe3F680CC0/sources/contracts/JBETHPaymentTerminal3_1_2.sol
Checks the balance of tokens in this contract. return The contract's balance, as a fixed point number with the same amount of decimals as this terminal.
function _balance() internal view override returns (uint256) { return address(this).balance; } uint256 _baseWeightCurrency, IJBOperatorStore _operatorStore, IJBProjects _projects, IJBDirectory _directory, IJBSplitsStore _splitsStore, IJBPrices _prices, address _store, address _owner ) JBPayoutRedemptionPaymentTerminal3_1_2( JBTokens.ETH, JBCurrencies.ETH, _baseWeightCurrency, JBSplitsGroups.ETH_PAYOUT, _operatorStore, _projects, _directory, _splitsStore, _prices, _store, _owner )
8,432,353
./partial_match/1/0xc4d57603D47FB842EC11A5332748f9F96d44cbEB/sources/src/contracts/FraxlendPair.sol
The ```getImmutableUint256``` function gets all uint256 config values return _oracleNormalization Oracle normalization factor return _maxLTV Maximum LTV return _cleanLiquidationFee Clean Liquidation Fee return _maturityDate Maturity Date return _penaltyRate Penalty Rate
function getImmutableUint256() external view returns ( uint256 _oracleNormalization, uint256 _maxLTV, uint256 _cleanLiquidationFee, uint256 _maturityDate, uint256 _penaltyRate ) { _oracleNormalization = oracleNormalization; _maxLTV = maxLTV; _cleanLiquidationFee = cleanLiquidationFee; _maturityDate = maturityDate; _penaltyRate = penaltyRate; }
3,702,485
/** *Submitted for verification at Etherscan.io on 2021-07-29 */ // Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libs/TransferHelper.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // 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,uint)'))); (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,uint)'))); (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,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/ICoFiXRouter.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods for CoFiXRouter interface ICoFiXRouter { /// @dev Register trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @param pool Pool for the trade pair function registerPair(address token0, address token1, address pool) external; /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function pairFor(address token0, address token1) external view returns (address pool); /// @dev Register routing path /// @param src Src token address /// @param dest Dest token address /// @param path Routing path function registerRouterPath(address src, address dest, address[] calldata path) external; /// @dev Get routing path from src token address to dest token address /// @param src Src token address /// @param dest Dest token address /// @return path If success, return the routing path, /// each address in the array represents the token address experienced during the trading function getRouterPath(address src, address dest) external view returns (address[] memory path); /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (address xtoken, uint liquidity); /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidityAndStake( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (address xtoken, uint liquidity); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// (notice: msg.value = oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The deadline of this request /// @return amountETH The real amount of ETH transferred from the pool /// @return amountToken The real amount of Token transferred from the pool function removeLiquidityGetTokenAndETH( address pool, address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountETH, uint amountToken); /// @dev Swap exact tokens for tokens /// @param path Routing path. If you need to exchange through multi-level routes, you need to write down all /// token addresses (ETH address is represented by 0) of the exchange path /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The minimum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The deadline of this request /// @return amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address[] calldata path, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint amountOut); /// @dev Acquire the transaction mining share of the target XToken /// @param xtoken The destination XToken address /// @return Target XToken's transaction mining share function getTradeReward(address xtoken) external view returns (uint); } // File contracts/interfaces/ICoFiXPool.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods and events for CoFiXPool interface ICoFiXPool { /* ****************************************************************************************** * Note: In order to unify the authorization entry, all transferFrom operations are carried * out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and * needs to be taken into account when calculating the pool balance before and after rollover * ******************************************************************************************/ /// @dev Add liquidity and mining xtoken event /// @param token Target token address /// @param to The address to receive xtoken /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidity The real liquidity or XToken minted from pool event Mint(address token, address to, uint amountETH, uint amountToken, uint liquidity); /// @dev Remove liquidity and burn xtoken event /// @param token The address of ERC20 Token /// @param to The target address receiving the Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHOut The real amount of ETH transferred from the pool /// @param amountTokenOut The real amount of Token transferred from the pool event Burn(address token, address to, uint liquidity, uint amountETHOut, uint amountTokenOut); /// @dev Set configuration /// @param theta Trade fee rate, ten thousand points system. 20 /// @param impactCostVOL Impact cost threshold /// @param nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based function setConfig(uint16 theta, uint96 impactCostVOL, uint96 nt) external; /// @dev Get configuration /// @return theta Trade fee rate, ten thousand points system. 20 /// @return impactCostVOL Impact cost threshold /// @return nt Each unit token (in the case of binary pools, eth) is used for the standard ore output, 1e18 based function getConfig() external view returns (uint16 theta, uint96 impactCostVOL, uint96 nt); /// @dev Add liquidity and mint xtoken /// @param token Target token address /// @param to The address to receive xtoken /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function mint( address token, address to, uint amountETH, uint amountToken, address payback ) external payable returns ( address xtoken, uint liquidity ); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// @param token The address of ERC20 Token /// @param to The target address receiving the Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountETHOut The real amount of ETH transferred from the pool /// @return amountTokenOut The real amount of Token transferred from the pool function burn( address token, address to, uint liquidity, address payback ) external payable returns ( uint amountETHOut, uint amountTokenOut ); /// @dev Swap token /// @param src Src token address /// @param dest Dest token address /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param to The target address receiving the ETH /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return amountOut The real amount of ETH transferred out of pool /// @return mined The amount of CoFi which will be mind by this trade function swap( address src, address dest, uint amountIn, address to, address payback ) external payable returns ( uint amountOut, uint mined ); /// @dev Gets the token address of the share obtained by the specified token market making /// @param token Target token address /// @return If the fund pool supports the specified token, return the token address of the market share function getXToken(address token) external view returns (address); } // File contracts/interfaces/ICoFiXVaultForStaking.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines methods for CoFiXVaultForStaking interface ICoFiXVaultForStaking { /// @dev Modify configuration /// @param cofiUnit CoFi mining unit function setConfig(uint cofiUnit) external; /// @dev Get configuration /// @return cofiUnit CoFi mining unit function getConfig() external view returns (uint cofiUnit); /// @dev Initialize ore drawing weight /// @param xtokens xtoken array /// @param weights weight array function batchSetPoolWeight(address[] calldata xtokens, uint[] calldata weights) external; /// @dev Get total staked amount of xtoken /// @param xtoken xtoken address (or CNode address) /// @return totalStaked Total lock volume of target xtoken /// @return cofiPerBlock Mining speed, cofi per block function getChannelInfo(address xtoken) external view returns (uint totalStaked, uint cofiPerBlock); /// @dev Get staked amount of target address /// @param xtoken xtoken address (or CNode address) /// @param addr Target address /// @return Staked amount of target address function balanceOf(address xtoken, address addr) external view returns (uint); /// @dev Get the number of CoFi to be collected by the target address on the designated transaction pair lock /// @param xtoken xtoken address (or CNode address) /// @param addr Target address /// @return The number of CoFi to be collected by the target address on the designated transaction lock function earned(address xtoken, address addr) external view returns (uint); /// @dev Stake xtoken to earn CoFi, this method is only for CoFiXRouter /// @param xtoken xtoken address (or CNode address) /// @param to Target address /// @param amount Stake amount function routerStake(address xtoken, address to, uint amount) external; /// @dev Stake xtoken to earn CoFi /// @param xtoken xtoken address (or CNode address) /// @param amount Stake amount function stake(address xtoken, uint amount) external; /// @dev Withdraw xtoken, and claim earned CoFi /// @param xtoken xtoken address (or CNode address) /// @param amount Withdraw amount function withdraw(address xtoken, uint amount) external; /// @dev Claim CoFi /// @param xtoken xtoken address (or CNode address) function getReward(address xtoken) external; } // File contracts/interfaces/ICoFiXDAO.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the DAO methods interface ICoFiXDAO { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of CoFiXDAO contract struct Config { // Redeem status, 1 means normal uint8 status; // The number of CoFi redeem per block. 100 uint16 cofiPerBlock; // The maximum number of CoFi in a single redeem. 30000 uint32 cofiLimit; // Price deviation limit, beyond this upper limit stop redeem (10000 based). 1000 uint16 priceDeviationLimit; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Set the exchange relationship between the token and the price of the anchored target currency. /// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places. /// so exchange = 1e6 * 1 ether / 1e18 = 1e6 /// @param token Address of origin token /// @param target Address of target anchor token /// @param exchange Exchange rate of token and target function setTokenExchange(address token, address target, uint exchange) external; /// @dev Get the exchange relationship between the token and the price of the anchored target currency. /// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places. /// so exchange = 1e6 * 1 ether / 1e18 = 1e6 /// @param token Address of origin token /// @return target Address of target anchor token /// @return exchange Exchange rate of token and target function getTokenExchange(address token) external view returns (address target, uint exchange); /// @dev Add reward /// @param pool Destination pool function addETHReward(address pool) external payable; /// @dev The function returns eth rewards of specified pool /// @param pool Destination pool function totalETHRewards(address pool) external view returns (uint); /// @dev Settlement /// @param pool Destination pool. Indicates which pool to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address pool, address tokenAddress, address to, uint value) external payable; /// @dev Redeem CoFi for ethers /// @notice Eth fee will be charged /// @param amount The amount of CoFi /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address function redeem(uint amount, address payback) external payable; /// @dev Redeem CoFi for Token /// @notice Eth fee will be charged /// @param token The target token /// @param amount The amount of CoFi /// @param payback As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address function redeemToken(address token, uint amount, address payback) external payable; /// @dev Get the current amount available for repurchase function quotaOf() external view returns (uint); } // File contracts/interfaces/ICoFiXMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for CoFiX builtin contract address mapping interface ICoFiXMapping { /// @dev Set the built-in contract address of the system /// @param cofiToken Address of CoFi token contract /// @param cofiNode Address of CoFi Node contract /// @param cofixDAO ICoFiXDAO implementation contract address /// @param cofixRouter ICoFiXRouter implementation contract address for CoFiX /// @param cofixController ICoFiXController implementation contract address /// @param cofixVaultForStaking ICoFiXVaultForStaking implementation contract address function setBuiltinAddress( address cofiToken, address cofiNode, address cofixDAO, address cofixRouter, address cofixController, address cofixVaultForStaking ) external; /// @dev Get the built-in contract address of the system /// @return cofiToken Address of CoFi token contract /// @return cofiNode Address of CoFi Node contract /// @return cofixDAO ICoFiXDAO implementation contract address /// @return cofixRouter ICoFiXRouter implementation contract address for CoFiX /// @return cofixController ICoFiXController implementation contract address function getBuiltinAddress() external view returns ( address cofiToken, address cofiNode, address cofixDAO, address cofixRouter, address cofixController, address cofixVaultForStaking ); /// @dev Get address of CoFi token contract /// @return Address of CoFi Node token contract function getCoFiTokenAddress() external view returns (address); /// @dev Get address of CoFi Node contract /// @return Address of CoFi Node contract function getCoFiNodeAddress() external view returns (address); /// @dev Get ICoFiXDAO implementation contract address /// @return ICoFiXDAO implementation contract address function getCoFiXDAOAddress() external view returns (address); /// @dev Get ICoFiXRouter implementation contract address for CoFiX /// @return ICoFiXRouter implementation contract address for CoFiX function getCoFiXRouterAddress() external view returns (address); /// @dev Get ICoFiXController implementation contract address /// @return ICoFiXController implementation contract address function getCoFiXControllerAddress() external view returns (address); /// @dev Get ICoFiXVaultForStaking implementation contract address /// @return ICoFiXVaultForStaking implementation contract address function getCoFiXVaultForStakingAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by CoFiX system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string calldata key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string calldata key) external view returns (address); } // File contracts/interfaces/ICoFiXGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface ICoFiXGovernance is ICoFiXMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/CoFiXBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // Router contract to interact with each CoFiXPair, no owner or governance /// @dev Base contract of CoFiX contract CoFiXBase { // Address of CoFiToken contract address constant COFI_TOKEN_ADDRESS = 0x1a23a6BfBAdB59fa563008c0fB7cf96dfCF34Ea1; // Address of CoFiNode contract address constant CNODE_TOKEN_ADDRESS = 0x558201DC4741efc11031Cdc3BC1bC728C23bF512; // Genesis block number of CoFi // CoFiToken contract is created at block height 11040156. However, because the mining algorithm of CoFiX1.0 // is different from that at present, a new mining algorithm is adopted from CoFiX2.1. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the CoFi begins to decay. According to the circulation when CoFi2.0 is online, the new mining // algorithm is used to deduce and convert the CoFi, and the new algorithm is used to mine the CoFiX2.1 // on-line flow, the actual block is 11040688 uint constant COFI_GENESIS_BLOCK = 11040688; /// @dev ICoFiXGovernance implementation contract address address public _governance; /// @dev To support open-zeppelin/upgrades /// @param governance ICoFiXGovernance implementation contract address function initialize(address governance) virtual public { require(_governance == address(0), "CoFiX:!initialize"); _governance = governance; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance ICoFiXGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || ICoFiXGovernance(governance).checkGovernance(msg.sender, 0), "CoFiX:!gov"); _governance = newGovernance; } /// @dev Migrate funds from current contract to CoFiXDAO /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = ICoFiXGovernance(_governance).getCoFiXDAOAddress(); if (tokenAddress == address(0)) { ICoFiXDAO(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(ICoFiXGovernance(_governance).checkGovernance(msg.sender, 0), "CoFiX:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "CoFiX:!contract"); _; } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/[email protected] // MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/CoFiToken.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // CoFiToken with Governance. It offers possibilities to adopt off-chain gasless governance infra. contract CoFiToken is ERC20("CoFi Token", "CoFi") { address public governance; mapping (address => bool) public minters; // Copied and modified from SUSHI code: // https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol // Which is copied and modified from YAM code and COMPOUND: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @dev An event thats emitted when a new governance account is set /// @param _new The new governance address event NewGovernance(address _new); /// @dev An event thats emitted when a new minter account is added /// @param _minter The new minter address added event MinterAdded(address _minter); /// @dev An event thats emitted when a minter account is removed /// @param _minter The minter address removed event MinterRemoved(address _minter); modifier onlyGovernance() { require(msg.sender == governance, "CoFi: !governance"); _; } constructor() { governance = msg.sender; } function setGovernance(address _new) external onlyGovernance { require(_new != address(0), "CoFi: zero addr"); require(_new != governance, "CoFi: same addr"); governance = _new; emit NewGovernance(_new); } function addMinter(address _minter) external onlyGovernance { minters[_minter] = true; emit MinterAdded(_minter); } function removeMinter(address _minter) external onlyGovernance { minters[_minter] = false; emit MinterRemoved(_minter); } /// @notice mint is used to distribute CoFi token to users, minters are CoFi mining pools function mint(address _to, uint _amount) external { require(minters[msg.sender], "CoFi: !minter"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice SUSHI has a vote governance bug in its token implementation, CoFi fixed it here /// read https://blog.peckshield.com/2020/09/08/sushi/ function transfer(address _recipient, uint _amount) public override returns (bool) { super.transfer(_recipient, _amount); _moveDelegates(_delegates[msg.sender], _delegates[_recipient], _amount); return true; } /// @notice override original transferFrom to fix vote issue function transferFrom(address _sender, address _recipient, uint _amount) public override returns (bool) { super.transferFrom(_sender, _recipient, _amount); _moveDelegates(_delegates[_sender], _delegates[_recipient], _amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CoFi::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CoFi::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "CoFi::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint) { require(blockNumber < block.number, "CoFi::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint delegatorBalance = balanceOf(delegator); // balance of underlying CoFis (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld - (amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld + (amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes ) internal { uint32 blockNumber = safe32(block.number, "CoFi::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } // File contracts/CoFiXRouter.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Router contract to interact with each CoFiXPair contract CoFiXRouter is CoFiXBase, ICoFiXRouter { /* ****************************************************************************************** * Note: In order to unify the authorization entry, all transferFrom operations are carried * out in the CoFiXRouter, and the CoFiXPool needs to be fixed, CoFiXRouter does trust and * needs to be taken into account when calculating the pool balance before and after rollover * ******************************************************************************************/ // Address of CoFiXVaultForStaking address _cofixVaultForStaking; // Mapping for trade pairs. keccak256(token0, token1)=>pool mapping(bytes32=>address) _pairs; // Mapping for trade paths. keccak256(token0, token1) = > path mapping(bytes32=>address[]) _paths; // Record the total CoFi share of CNode uint _cnodeReward; /// @dev Create CoFiXRouter constructor () { } // Verify that the cutoff time has exceeded modifier ensure(uint deadline) { require(block.timestamp <= deadline, "CoFiXRouter: EXPIRED"); _; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance ICoFiXGovernance implementation contract address function update(address newGovernance) public override { super.update(newGovernance); _cofixVaultForStaking = ICoFiXGovernance(newGovernance).getCoFiXVaultForStakingAddress(); } /// @dev Register trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @param pool Pool for the trade pair function registerPair(address token0, address token1, address pool) public override onlyGovernance { _pairs[_getKey(token0, token1)] = pool; } /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function pairFor(address token0, address token1) external view override returns (address pool) { return _pairFor(token0, token1); } /// @dev Register routing path /// @param src Src token address /// @param dest Dest token address /// @param path Routing path function registerRouterPath(address src, address dest, address[] calldata path) external override onlyGovernance { // Check that the source and destination addresses are correct require(src == path[0], "CoFiXRouter: first token error"); require(dest == path[path.length - 1], "CoFiXRouter: last token error"); // Register routing path _paths[_getKey(src, dest)] = path; } /// @dev Get routing path from src token address to dest token address /// @param src Src token address /// @param dest Dest token address /// @return path If success, return the routing path, /// each address in the array represents the token address experienced during the trading function getRouterPath(address src, address dest) external view override returns (address[] memory path) { // Load the routing path path = _paths[_getKey(src, dest)]; uint j = path.length; // If it is a reverse path, reverse the path require(j > 0, "CoFiXRouter: path not exist"); if (src == path[--j] && dest == path[0]) { for (uint i = 0; i < j;) { address tmp = path[i]; path[i++] = path[j]; path[j--] = tmp; } } else { require(src == path[0] && dest == path[j], "CoFiXRouter: path error"); } } /// @dev Get pool address for trade pair /// @param token0 pair-token0. 0 address means eth /// @param token1 pair-token1. 0 address means eth /// @return pool Pool for the trade pair function _pairFor(address token0, address token1) private view returns (address pool) { return _pairs[_getKey(token0, token1)]; } // Generate the mapping key based on the token address function _getKey(address token0, address token1) private pure returns (bytes32) { (token0, token1) = _sort(token0, token1); return keccak256(abi.encodePacked(token0, token1)); } // Sort the address pair function _sort(address token0, address token1) private pure returns (address min, address max) { if (token0 < token1) { min = token0; max = token1; } else { min = token1; max = token0; } } /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (address xtoken, uint liquidity) { // 1. Transfer token to pool if (token != address(0)) { TransferHelper.safeTransferFrom(token, msg.sender, pool, amountToken); } // 2. Add liquidity, and increase xtoken (xtoken, liquidity) = ICoFiXPool(pool).mint { value: msg.value } (token, to, amountETH, amountToken, to); // The number of shares should not be lower than the expected minimum value require(liquidity >= liquidityMin, "CoFiXRouter: less liquidity than expected"); } /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically /// (notice: msg.value = amountETH + oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool. (When pool is AnchorPool, amountETH is 0) /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The deadline of this request /// @return xtoken The liquidity share token address obtained /// @return liquidity The real liquidity or XToken minted from pool function addLiquidityAndStake( address pool, address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (address xtoken, uint liquidity) { // 1. Transfer token to pool if (token != address(0)) { TransferHelper.safeTransferFrom(token, msg.sender, pool, amountToken); } // 2. Add liquidity, and increase xtoken address cofixVaultForStaking = _cofixVaultForStaking; (xtoken, liquidity) = ICoFiXPool(pool).mint { value: msg.value } (token, cofixVaultForStaking, amountETH, amountToken, to); // The number of shares should not be lower than the expected minimum value require(liquidity >= liquidityMin, "CoFiXRouter: less liquidity than expected"); // 3. Stake xtoken to CoFiXVaultForStaking ICoFiXVaultForStaking(cofixVaultForStaking).routerStake(xtoken, to, liquidity); } /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) /// (notice: msg.value = oracle fee) /// @param pool The address of pool /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The deadline of this request /// @return amountETH The real amount of ETH transferred from the pool /// @return amountToken The real amount of Token transferred from the pool function removeLiquidityGetTokenAndETH( address pool, address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint amountETH, uint amountToken) { // 0. Get xtoken corresponding to the token address xtoken = ICoFiXPool(pool).getXToken(token); // 1. Transfer xtoken to pool TransferHelper.safeTransferFrom(xtoken, msg.sender, pool, liquidity); // 2. Remove liquidity and return tokens (amountETH, amountToken) = ICoFiXPool(pool).burn { value: msg.value } (token, to, liquidity, to); // 3. amountETH must not less than expected require(amountETH >= amountETHMin, "CoFiXRouter: less eth than expected"); } /// @dev Swap exact tokens for tokens /// @param path Routing path. If you need to exchange through multi-level routes, you need to write down all /// token addresses (ETH address is represented by 0) of the exchange path /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The minimum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The deadline of this request /// @return amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address[] calldata path, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable override ensure(deadline) returns (uint amountOut) { uint mined; if (path.length == 2) { address src = path[0]; address dest = path[1]; // 0. Get pool address for trade pair address pool = _pairFor(src, dest); // 1. Transfer token to the pool if (src != address(0)) { TransferHelper.safeTransferFrom(src, msg.sender, pool, amountIn); } // 2. Trade (amountOut, mined) = ICoFiXPool(pool).swap { value: msg.value } (src, dest, amountIn, to, to); } else { // 1. Trade (amountOut, mined) = _swap(path, amountIn, to); // 2. Any remaining ETH in the Router is considered to be the user's and is forwarded to // the address specified by the Router uint balance = address(this).balance; if (balance > 0) { payable(to).transfer(balance); } } // 3. amountOut must not less than expected require(amountOut >= amountOutMin, "CoFiXRouter: got less than expected"); // 4. Mining cofi for trade _mint(mined, rewardTo); } // Trade function _swap( address[] calldata path, uint amountIn, address to ) private returns ( uint amountOut, uint totalMined ) { // Initialize totalMined = 0; // Get the first pair address token0 = path[0]; address token1 = path[1]; address pool = _pairFor(token0, token1); // Transfer token to first pool if (token0 != address(0)) { TransferHelper.safeTransferFrom(token0, to, pool, amountIn); } uint mined; // Execute the exchange transaction according to the routing path for (uint i = 1; ; ) { // Address to receive funds for this transaction address recv = to; // Next token address. 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF means empty address next = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; if (++i < path.length) { next = path[i]; // While the next token address still exists, the fund receiving address is the next transaction pair recv = _pairFor(token1, next); } // Perform an exchange transaction. If token1 is ETH, the fund receiving address is address(this). // Q: The solution of openzeppelin-upgrades may cause transfer eth fail, // It needs to be validated and resolved // A: Since the execution entry is at CoFiXRouter, the proxy address of the CoFiXRouter has // already been read, which reduces the gas consumption for subsequent reads, So the gas // consumption of the later receive() transfer to CoFiXRouter is reduced without an error, // so OpenZeppelin is now available, The upgradable solution of does not cause the problem // of converting ETH from the capital pool to CoFixRouter to fail. (amountIn, mined) = ICoFiXPool(pool).swap { value: address(this).balance } (token0, token1, amountIn, token1 == address(0) ? address(this) : recv, address(this)); // Increase total mining totalMined += mined; // Record the amount of money exchanged this time //amounts[i - 1] = amountIn; // next equal to 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF means trade is over if (next == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) { break; } // Switch to the next trade pair in the routing path token0 = token1; token1 = next; pool = recv; } amountOut = amountIn; } // Mint CoFi to target address, and increase for CNode function _mint(uint mined, address rewardTo) private { if (mined > 0) { uint cnodeReward = mined / 10; // The amount available to the trader CoFiToken(COFI_TOKEN_ADDRESS).mint(rewardTo, mined - cnodeReward); // Increase for CNode _cnodeReward += cnodeReward; } } /// @dev Acquire the transaction mining share of the target XToken /// @param xtoken The destination XToken address /// @return Target XToken's transaction mining share function getTradeReward(address xtoken) external view override returns (uint) { // Only CNode has a share of trading out, not market making if (xtoken == CNODE_TOKEN_ADDRESS) { return _cnodeReward; } return 0; } receive() external payable { } }
Trade Initialize Get the first pair Transfer token to first pool Execute the exchange transaction according to the routing path Address to receive funds for this transaction Next token address. 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF means empty While the next token address still exists, the fund receiving address is the next transaction pair Perform an exchange transaction. If token1 is ETH, the fund receiving address is address(this). Q: The solution of openzeppelin-upgrades may cause transfer eth fail, It needs to be validated and resolved A: Since the execution entry is at CoFiXRouter, the proxy address of the CoFiXRouter has already been read, which reduces the gas consumption for subsequent reads, So the gas consumption of the later receive() transfer to CoFiXRouter is reduced without an error, so OpenZeppelin is now available, The upgradable solution of does not cause the problem of converting ETH from the capital pool to CoFixRouter to fail. next equal to 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF means trade is over
function _swap( address[] calldata path, uint amountIn, address to ) private returns ( uint amountOut, uint totalMined ) { totalMined = 0; address token0 = path[0]; address token1 = path[1]; address pool = _pairFor(token0, token1); if (token0 != address(0)) { TransferHelper.safeTransferFrom(token0, to, pool, amountIn); } uint mined; for (uint i = 1; ; ) { address recv = to; address next = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; if (++i < path.length) { next = path[i]; recv = _pairFor(token1, next); } (amountIn, mined) = ICoFiXPool(pool).swap { value: address(this).balance } (token0, token1, amountIn, token1 == address(0) ? address(this) : recv, address(this)); if (next == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) { break; } token1 = next; pool = recv; } amountOut = amountIn; }
2,185,569
./full_match/4/0xe55FDf1fc08771524Ff148B09E7B7323939248Fc/sources/browser/ALWN.sol
- return Number of keys/
function getPoolsCount() public view returns(uint256) { return poolInfo.length; }
652,219
pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); // KYBER-NOTE! code changed to comply with ERC20 standard event Transfer(address indexed _from, address indexed _to, uint _value); //event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); // KYBER-NOTE! code changed to comply with ERC20 standard event Approval(address indexed _owner, address indexed _spender, uint _value); //event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _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); // KYBER-NOTE! code changed to comply with ERC20 standard balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); //balances[_from] = balances[_from].sub(_value); // this was removed allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract REKTTokenSale { using SafeMath for uint; address public admin; address public REKTMultiSigWallet; REKT public token; bool public haltSale; function REKTTokenSale( address _admin, address _REKTMultiSigWallet, REKT _token) { admin = _admin; REKTMultiSigWallet = _REKTMultiSigWallet; token = _token; } function setHaltSale( bool halt ) { require( msg.sender == admin ); haltSale = halt; } function() payable { buy( msg.sender ); } event Buy( address _buyer, uint _tokens, uint _payedWei ); function buy( address recipient ) payable returns(uint){ require( ! haltSale ); // send payment to wallet sendETHToMultiSig( msg.value ); uint receivedTokens = msg.value.mul( 1000 ); assert( token.transfer( recipient, receivedTokens ) ); Buy( recipient, receivedTokens, msg.value ); return msg.value; } function sendETHToMultiSig( uint value ) internal { REKTMultiSigWallet.transfer( value ); } // ETH balance is always expected to be 0. // but in case something went wrong, we use this function to extract the eth. function emergencyDrain(ERC20 anyToken) returns(bool){ require( msg.sender == admin ); if( this.balance > 0 ) { sendETHToMultiSig( this.balance ); } if( anyToken != address(0x0) ) { assert( anyToken.transfer(REKTMultiSigWallet, anyToken.balanceOf(this)) ); } return true; } } contract REKT is StandardToken, Ownable { string public constant name = "REKT"; string public constant symbol = "REKT"; uint public constant decimals = 18; address public tokenSaleContract; modifier validDestination( address to ) { require(to != address(0x0)); require(to != address(this) ); _; } function REKT( uint tokenTotalAmount, address admin ) { // Mint all tokens. Then disable minting forever. balances[msg.sender] = tokenTotalAmount.div(2); balances[admin] = tokenTotalAmount.div(2); totalSupply = tokenTotalAmount; Transfer(address(0x0), msg.sender, tokenTotalAmount); tokenSaleContract = msg.sender; transferOwnership(admin); // admin could drain tokens that were sent here by mistake } function transfer(address _to, uint _value) validDestination(_to) returns (bool) { return super.transfer(_to, _value); } function setTokenSaleContract(address _tokenSaleContract) onlyOwner { tokenSaleContract = _tokenSaleContract; } function transferFrom(address _from, address _to, uint _value) validDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } event Burn(address indexed _burner, uint _value); function burn(uint _value) returns (bool){ balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); Transfer(msg.sender, address(0x0), _value); return true; } // save some gas by making only one contract call function burnFrom(address _from, uint256 _value) returns (bool) { assert( transferFrom( _from, msg.sender, _value ) ); return burn(_value); } function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner { token.transfer( owner, amount ); } }
save some gas by making only one contract call
function burnFrom(address _from, uint256 _value) returns (bool) { assert( transferFrom( _from, msg.sender, _value ) ); return burn(_value); }
15,119,637
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; // @title Simple MultiSig Wallet // @author Saurav Kanchan contract Wallet { // EIP712 Precomputed hashes: // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)") bytes32 private constant EIP712DOMAINTYPE_HASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472; // keccak256("Simple MultiSig Wallet") bytes32 private constant NAME_HASH = 0x3e6b336688739eb28fb1cb4076d6b7bd95a261dae357a212de0d58fe51c68128; // keccak256("1") bytes32 private constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; // solhint-disable-next-line // keccak256("MultiSigTransaction(address destination,uint256 value,bytes data,uint256 nonce,address executor,uint256 gasLimit)") bytes32 private constant TXTYPE_HASH = 0x3ee892349ae4bbe61dce18f95115b5dc02daf49204cc602458cd4c1f540d56d7; // Disambiguating salt for the EIP 712 protocol bytes32 private constant SALT = 0xdbfa5a2ed8eaf81bdaec2b889699814aa810a7653c8402c0a286fa1bfa105f5b; uint256 public nonce; // (only) mutable state uint256 public threshold; // immutable state mapping(address => bool) public isOwner; // immutable state address[] public ownersArr; // immutable state bytes32 private domainSeperator; // hash for EIP712, computed from contract address // Note that owners_ must be strictly increasing, in order to prevent duplicates constructor( uint256 threshold_, address[] memory owners_, uint256 chainId ) { require(owners_.length <= 10, "Maximum 10 owners can be added"); require(threshold_ <= owners_.length, "Threshold must be less than or equal to number of owners"); require(threshold_ > 0, "Minimum 1 threshold is required"); address lastAdd = address(0); for (uint256 i = 0; i < owners_.length; i++) { require(owners_[i] > lastAdd, "In order to prevent duplciates pass owners in ascending order"); isOwner[owners_[i]] = true; lastAdd = owners_[i]; } ownersArr = owners_; threshold = threshold_; domainSeperator = keccak256(abi.encode(EIP712DOMAINTYPE_HASH, NAME_HASH, VERSION_HASH, chainId, this, SALT)); } event SafeReceived(address indexed sender, uint256 value); /// @dev Fallback function accepts Ether transactions. receive() external payable { emit SafeReceived(msg.sender, msg.value); } function execute( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address destination, uint256 value, bytes memory data, address executor, uint256 gasLimit ) public { require(sigR.length >= threshold, "Below threshold"); require(sigR.length == sigS.length && sigR.length == sigV.length, "Length of array of R, S and V should match"); require(executor == msg.sender, "Persona calling the fuction should be passed as executor"); // EIP712 scheme: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md bytes32 txInputHash = keccak256(abi.encode(TXTYPE_HASH, destination, value, keccak256(data), nonce, executor, gasLimit)); // RLP Encoding: https://blog.ricmoo.com/verifying-messages-in-solidity-50a94f82b2ca bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n64", domainSeperator, txInputHash)); address lastAdd = address(0); // cannot have address(0) as an owner for (uint256 i = 0; i < threshold; i++) { address recovered = ecrecover(totalHash, sigV[i], sigR[i], sigS[i]); require(recovered > lastAdd, "In order to prevent duplciates pass owners in ascending order"); require(isOwner[recovered], "Singer is not the owner of multisg wallet"); lastAdd = recovered; } // If we make it here all signatures are accounted for. // The address.call() syntax is no longer recommended, see: // https://github.com/ethereum/solidity/issues/2884 nonce = nonce + 1; bool success = false; // solhint-disable-next-line no-inline-assembly assembly { success := call(gasLimit, destination, value, add(data, 0x20), mload(data), 0, 0) } require(success, "Transaction Failed"); } }
EIP712 scheme: https:github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md RLP Encoding: https:blog.ricmoo.com/verifying-messages-in-solidity-50a94f82b2ca solhint-disable-next-line no-inline-assembly
function execute( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address destination, uint256 value, bytes memory data, address executor, uint256 gasLimit ) public { require(sigR.length >= threshold, "Below threshold"); require(sigR.length == sigS.length && sigR.length == sigV.length, "Length of array of R, S and V should match"); require(executor == msg.sender, "Persona calling the fuction should be passed as executor"); bytes32 txInputHash = keccak256(abi.encode(TXTYPE_HASH, destination, value, keccak256(data), nonce, executor, gasLimit)); bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n64", domainSeperator, txInputHash)); for (uint256 i = 0; i < threshold; i++) { address recovered = ecrecover(totalHash, sigV[i], sigR[i], sigS[i]); require(recovered > lastAdd, "In order to prevent duplciates pass owners in ascending order"); require(isOwner[recovered], "Singer is not the owner of multisg wallet"); lastAdd = recovered; } bool success = false; assembly { success := call(gasLimit, destination, value, add(data, 0x20), mload(data), 0, 0) } require(success, "Transaction Failed"); }
1,002,298
./full_match/1/0xB3d4c579fbe764027f0e8e1Bbc5EcdB70DEfAd35/sources/contracts/minting/CombinatorSimpleReRoll.sol
Checks if a given address is on the merkle tree allowlist Merkle trees can be generated using https://github.com/OpenZeppelin/merkle-tree account The address to check merkleProof The merkle proof to check return Whether the address is on the allowlist or not
function isValidMerkleProof( address account, bytes32[] calldata merkleProof ) public view virtual returns (bool) { return MerkleProof.verifyCalldata( merkleProof, _merkleRoot, keccak256(bytes.concat(keccak256(abi.encode(account)))) ); }
16,419,390
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../utility/ContractRegistryClient.sol"; import "../token/interfaces/IDSToken.sol"; import "./interfaces/IConverter.sol"; import "./interfaces/IConverterFactory.sol"; import "./interfaces/IConverterRegistry.sol"; import "./interfaces/IConverterRegistryData.sol"; /** * @dev This contract maintains a list of all active converters in the Bancor Network. * * Since converters can be upgraded and thus their address can change, the registry actually keeps * converter anchors internally and not the converters themselves. * The active converter for each anchor can be easily accessed by querying the anchor's owner. * * The registry exposes 3 different lists that can be accessed and iterated, based on the use-case of the caller: * - Anchors - can be used to get all the latest / historical data in the network * - Liquidity pools - can be used to get all liquidity pools for funding, liquidation etc. * - Convertible tokens - can be used to get all tokens that can be converted in the network (excluding pool * tokens), and for each one - all anchors that hold it in their reserves * * * The contract fires events whenever one of the primitives is added to or removed from the registry * * The contract is upgradable. */ contract ConverterRegistry is IConverterRegistry, ContractRegistryClient { /** * @dev triggered when a converter anchor is added to the registry */ event ConverterAnchorAdded(IConverterAnchor indexed anchor); /** * @dev triggered when a converter anchor is removed from the registry */ event ConverterAnchorRemoved(IConverterAnchor indexed anchor); /** * @dev triggered when a liquidity pool is added to the registry */ event LiquidityPoolAdded(IConverterAnchor indexed liquidityPool); /** * @dev triggered when a liquidity pool is removed from the registry */ event LiquidityPoolRemoved(IConverterAnchor indexed liquidityPool); /** * @dev triggered when a convertible token is added to the registry */ event ConvertibleTokenAdded(IReserveToken indexed convertibleToken, IConverterAnchor indexed smartToken); /** * @dev triggered when a convertible token is removed from the registry */ event ConvertibleTokenRemoved(IReserveToken indexed convertibleToken, IConverterAnchor indexed smartToken); /** * @dev deprecated, backward compatibility, use `ConverterAnchorAdded` */ event SmartTokenAdded(IConverterAnchor indexed smartToken); /** * @dev deprecated, backward compatibility, use `ConverterAnchorRemoved` */ event SmartTokenRemoved(IConverterAnchor indexed smartToken); /** * @dev initializes a new ConverterRegistry instance */ constructor(IContractRegistry registry) public ContractRegistryClient(registry) {} /** * @dev creates an empty liquidity pool and adds its converter to the registry */ function newConverter( uint16 converterType, string memory name, string memory symbol, uint8 decimals, uint32 maxConversionFee, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights ) public virtual returns (IConverter) { uint256 length = reserveTokens.length; require(length == reserveWeights.length, "ERR_INVALID_RESERVES"); // for standard pools, change type 1 to type 3 if (converterType == 1 && _isStandardPool(reserveWeights)) { converterType = 3; } require( getLiquidityPoolByConfig(converterType, reserveTokens, reserveWeights) == IConverterAnchor(0), "ERR_ALREADY_EXISTS" ); IConverterFactory factory = IConverterFactory(_addressOf(CONVERTER_FACTORY)); IConverterAnchor anchor = IConverterAnchor(factory.createAnchor(converterType, name, symbol, decimals)); IConverter converter = IConverter(factory.createConverter(converterType, anchor, registry(), maxConversionFee)); anchor.acceptOwnership(); converter.acceptOwnership(); for (uint256 i = 0; i < length; i++) { converter.addReserve(reserveTokens[i], reserveWeights[i]); } anchor.transferOwnership(address(converter)); converter.acceptAnchorOwnership(); converter.transferOwnership(msg.sender); _addConverter(converter); return converter; } /** * @dev adds an existing converter to the registry * * Requirements: * * - the caller must be the owner of the contract */ function addConverter(IConverter converter) public ownerOnly { require(isConverterValid(converter), "ERR_INVALID_CONVERTER"); _addConverter(converter); } /** * @dev removes a converter from the registry * * * Requirements: * * - anyone can remove an existing converter from the registry, as long as the converter is invalid, but only the * owner can also remove valid converters */ function removeConverter(IConverter converter) public { require(msg.sender == owner() || !isConverterValid(converter), "ERR_ACCESS_DENIED"); _removeConverter(converter); } /** * @dev returns the number of converter anchors in the registry */ function getAnchorCount() public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokenCount(); } /** * @dev returns the list of converter anchors in the registry */ function getAnchors() public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokens(); } /** * @dev returns the converter anchor at a given index */ function getAnchor(uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartToken(index); } /** * @dev checks whether or not a given value is a converter anchor */ function isAnchor(address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isSmartToken(value); } /** * @dev returns the number of liquidity pools in the registry */ function getLiquidityPoolCount() public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPoolCount(); } /** * @dev returns the list of liquidity pools in the registry */ function getLiquidityPools() public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPools(); } /** * @dev returns the liquidity pool at a given index */ function getLiquidityPool(uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPool(index); } /** * @dev checks whether or not a given value is a liquidity pool */ function isLiquidityPool(address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isLiquidityPool(value); } /** * @dev returns the number of convertible tokens in the registry */ function getConvertibleTokenCount() public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenCount(); } /** * @dev returns the list of convertible tokens in the registry */ function getConvertibleTokens() public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokens(); } /** * @dev returns the convertible token at a given index */ function getConvertibleToken(uint256 index) public view override returns (IReserveToken) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleToken(index); } /** * @dev checks whether or not a given value is a convertible token */ function isConvertibleToken(address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleToken(value); } /** * @dev returns the number of converter anchors associated with a given convertible token */ function getConvertibleTokenAnchorCount(IReserveToken convertibleToken) public view override returns (uint256) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokenCount( convertibleToken ); } /** * @dev returns the list of converter anchors associated with a given convertible token */ function getConvertibleTokenAnchors(IReserveToken convertibleToken) public view override returns (address[] memory) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokens( convertibleToken ); } /** * @dev returns the converter anchor associated with a given convertible token at a given index */ function getConvertibleTokenAnchor(IReserveToken convertibleToken, uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartToken( convertibleToken, index ); } /** * @dev checks whether or not a given value is a converter anchor of a given convertible token */ function isConvertibleTokenAnchor(IReserveToken convertibleToken, address value) public view override returns (bool) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleTokenSmartToken( convertibleToken, value ); } /** * @dev returns a list of converters for a given list of anchors */ function getConvertersByAnchors(address[] memory anchors) public view returns (IConverter[] memory) { IConverter[] memory converters = new IConverter[](anchors.length); for (uint256 i = 0; i < anchors.length; i++) { converters[i] = IConverter(payable(IConverterAnchor(anchors[i]).owner())); } return converters; } /** * @dev checks whether or not a given converter is valid */ function isConverterValid(IConverter converter) public view returns (bool) { // verify that the converter is active return converter.token().owner() == address(converter); } /** * @dev checks if a liquidity pool with given configuration is already registered */ function isSimilarLiquidityPoolRegistered(IConverter converter) public view returns (bool) { uint256 reserveTokenCount = converter.connectorTokenCount(); IReserveToken[] memory reserveTokens = new IReserveToken[](reserveTokenCount); uint32[] memory reserveWeights = new uint32[](reserveTokenCount); // get the reserve-configuration of the converter for (uint256 i = 0; i < reserveTokenCount; i++) { IReserveToken reserveToken = converter.connectorTokens(i); reserveTokens[i] = reserveToken; reserveWeights[i] = _getReserveWeight(converter, reserveToken); } // return if a liquidity pool with the same configuration is already registered return getLiquidityPoolByConfig(_getConverterType(converter, reserveTokenCount), reserveTokens, reserveWeights) != IConverterAnchor(0); } /** * @dev searches for a liquidity pool with specific configuration */ function getLiquidityPoolByConfig( uint16 converterType, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights ) public view override returns (IConverterAnchor) { // verify that the input parameters represent a valid liquidity pool if (reserveTokens.length == reserveWeights.length && reserveTokens.length > 1) { // get the anchors of the least frequent token (optimization) address[] memory convertibleTokenAnchors = _getLeastFrequentTokenAnchors(reserveTokens); // search for a converter with the same configuration for (uint256 i = 0; i < convertibleTokenAnchors.length; i++) { IConverterAnchor anchor = IConverterAnchor(convertibleTokenAnchors[i]); IConverter converter = IConverter(payable(anchor.owner())); if (_isConverterReserveConfigEqual(converter, converterType, reserveTokens, reserveWeights)) { return anchor; } } } return IConverterAnchor(0); } /** * @dev adds a converter anchor to the registry */ function _addAnchor(IConverterRegistryData converterRegistryData, IConverterAnchor anchor) internal { converterRegistryData.addSmartToken(anchor); emit ConverterAnchorAdded(anchor); emit SmartTokenAdded(anchor); } /** * @dev removes a converter anchor from the registry */ function _removeAnchor(IConverterRegistryData converterRegistryData, IConverterAnchor anchor) internal { converterRegistryData.removeSmartToken(anchor); emit ConverterAnchorRemoved(anchor); emit SmartTokenRemoved(anchor); } /** * @dev adds a liquidity pool to the registry */ function _addLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor) internal { converterRegistryData.addLiquidityPool(liquidityPoolAnchor); emit LiquidityPoolAdded(liquidityPoolAnchor); } /** * @dev removes a liquidity pool from the registry */ function _removeLiquidityPool(IConverterRegistryData converterRegistryData, IConverterAnchor liquidityPoolAnchor) internal { converterRegistryData.removeLiquidityPool(liquidityPoolAnchor); emit LiquidityPoolRemoved(liquidityPoolAnchor); } /** * @dev adds a convertible token to the registry */ function _addConvertibleToken( IConverterRegistryData converterRegistryData, IReserveToken convertibleToken, IConverterAnchor anchor ) internal { converterRegistryData.addConvertibleToken(convertibleToken, anchor); emit ConvertibleTokenAdded(convertibleToken, anchor); } /** * @dev removes a convertible token from the registry */ function _removeConvertibleToken( IConverterRegistryData converterRegistryData, IReserveToken convertibleToken, IConverterAnchor anchor ) internal { converterRegistryData.removeConvertibleToken(convertibleToken, anchor); emit ConvertibleTokenRemoved(convertibleToken, anchor); } /** * @dev checks whether or not a given configuration depicts a standard pool */ function _isStandardPool(uint32[] memory reserveWeights) internal pure virtual returns (bool) { return reserveWeights.length == 2 && reserveWeights[0] == PPM_RESOLUTION / 2 && reserveWeights[1] == PPM_RESOLUTION / 2; } function _addConverter(IConverter converter) private { IConverterRegistryData converterRegistryData = IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)); IConverterAnchor anchor = IConverter(converter).token(); uint256 reserveTokenCount = converter.connectorTokenCount(); // add the converter anchor _addAnchor(converterRegistryData, anchor); if (reserveTokenCount > 1) { _addLiquidityPool(converterRegistryData, anchor); } else { _addConvertibleToken(converterRegistryData, IReserveToken(address(anchor)), anchor); } // add all reserve tokens for (uint256 i = 0; i < reserveTokenCount; i++) { _addConvertibleToken(converterRegistryData, converter.connectorTokens(i), anchor); } } function _removeConverter(IConverter converter) private { IConverterRegistryData converterRegistryData = IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)); IConverterAnchor anchor = IConverter(converter).token(); uint256 reserveTokenCount = converter.connectorTokenCount(); // remove the converter anchor _removeAnchor(converterRegistryData, anchor); if (reserveTokenCount > 1) { _removeLiquidityPool(converterRegistryData, anchor); } else { _removeConvertibleToken(converterRegistryData, IReserveToken(address(anchor)), anchor); } // remove all reserve tokens for (uint256 i = 0; i < reserveTokenCount; i++) { _removeConvertibleToken(converterRegistryData, converter.connectorTokens(i), anchor); } } function _getLeastFrequentTokenAnchors(IReserveToken[] memory reserveTokens) private view returns (address[] memory) { IConverterRegistryData converterRegistryData = IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)); uint256 minAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount(reserveTokens[0]); uint256 index = 0; // find the reserve token which has the smallest number of converter anchors for (uint256 i = 1; i < reserveTokens.length; i++) { uint256 convertibleTokenAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount( reserveTokens[i] ); if (minAnchorCount > convertibleTokenAnchorCount) { minAnchorCount = convertibleTokenAnchorCount; index = i; } } return converterRegistryData.getConvertibleTokenSmartTokens(reserveTokens[index]); } function _isConverterReserveConfigEqual( IConverter converter, uint16 converterType, IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights ) private view returns (bool) { uint256 reserveTokenCount = converter.connectorTokenCount(); if (converterType != _getConverterType(converter, reserveTokenCount)) { return false; } if (reserveTokens.length != reserveTokenCount) { return false; } for (uint256 i = 0; i < reserveTokens.length; i++) { if (reserveWeights[i] != _getReserveWeight(converter, reserveTokens[i])) { return false; } } return true; } // utility to get the reserve weight (including from older converters that don't support the new _getReserveWeight function) function _getReserveWeight(IConverter converter, IReserveToken reserveToken) private view returns (uint32) { (, uint32 weight, , , ) = converter.connectors(reserveToken); return weight; } bytes4 private constant CONVERTER_TYPE_FUNC_SELECTOR = bytes4(keccak256("converterType()")); // utility to get the converter type (including from older converters that don't support the new converterType function) function _getConverterType(IConverter converter, uint256 reserveTokenCount) private view returns (uint16) { (bool success, bytes memory returnData) = address(converter).staticcall( abi.encodeWithSelector(CONVERTER_TYPE_FUNC_SELECTOR) ); if (success && returnData.length == 32) { return abi.decode(returnData, (uint16)); } return reserveTokenCount > 1 ? 1 : 0; } /** * @dev deprecated, backward compatibility, use `getAnchorCount` */ function getSmartTokenCount() public view returns (uint256) { return getAnchorCount(); } /** * @dev deprecated, backward compatibility, use `getAnchors` */ function getSmartTokens() public view returns (address[] memory) { return getAnchors(); } /** * @dev deprecated, backward compatibility, use `getAnchor` */ function getSmartToken(uint256 index) public view returns (IConverterAnchor) { return getAnchor(index); } /** * @dev deprecated, backward compatibility, use `isAnchor` */ function isSmartToken(address value) public view returns (bool) { return isAnchor(value); } /** * @dev deprecated, backward compatibility, use `getConvertibleTokenAnchorCount` */ function getConvertibleTokenSmartTokenCount(IReserveToken convertibleToken) public view returns (uint256) { return getConvertibleTokenAnchorCount(convertibleToken); } /** * @dev deprecated, backward compatibility, use `getConvertibleTokenAnchors` */ function getConvertibleTokenSmartTokens(IReserveToken convertibleToken) public view returns (address[] memory) { return getConvertibleTokenAnchors(convertibleToken); } /** * @dev deprecated, backward compatibility, use `getConvertibleTokenAnchor` */ function getConvertibleTokenSmartToken(IReserveToken convertibleToken, uint256 index) public view returns (IConverterAnchor) { return getConvertibleTokenAnchor(convertibleToken, index); } /** * @dev deprecated, backward compatibility, use `isConvertibleTokenAnchor` */ function isConvertibleTokenSmartToken(IReserveToken convertibleToken, address value) public view returns (bool) { return isConvertibleTokenAnchor(convertibleToken, value); } /** * @dev deprecated, backward compatibility, use `getConvertersByAnchors` */ function getConvertersBySmartTokens(address[] memory smartTokens) public view returns (IConverter[] memory) { return getConvertersByAnchors(smartTokens); } /** * @dev deprecated, backward compatibility, use `getLiquidityPoolByConfig` */ function getLiquidityPoolByReserveConfig(IReserveToken[] memory reserveTokens, uint32[] memory reserveWeights) public view returns (IConverterAnchor) { return getLiquidityPoolByConfig(reserveTokens.length > 1 ? 1 : 0, reserveTokens, reserveWeights); } }
returns the converter anchor at a given index/
function getAnchor(uint256 index) public view override returns (IConverterAnchor) { return IConverterRegistryData(_addressOf(CONVERTER_REGISTRY_DATA)).getSmartToken(index); }
14,085,364
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {GnosisAuction} from "../../libraries/GnosisAuction.sol"; import { RibbonDeltaVaultStorage } from "../../storage/RibbonDeltaVaultStorage.sol"; import {Vault} from "../../libraries/Vault.sol"; import {VaultLifecycle} from "../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../libraries/ShareMath.sol"; import {RibbonVault} from "./base/RibbonVault.sol"; import {IRibbonThetaVault} from "../../interfaces/IRibbonThetaVault.sol"; /** * UPGRADEABILITY: Since we use the upgradeable proxy pattern, we must observe * the inheritance chain closely. * Any changes/appends in storage variable needs to happen in RibbonDeltaVaultStorage. * RibbonDeltaVault should not inherit from any other contract aside from RibbonVault, RibbonDeltaVaultStorage */ contract RibbonDeltaVault is RibbonVault, RibbonDeltaVaultStorage { using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; /************************************************ * EVENTS ***********************************************/ event OpenLong( address indexed options, uint256 purchaseAmount, uint256 premium, address indexed manager ); event CloseLong( address indexed options, uint256 profitAmount, address indexed manager ); event NewOptionAllocationSet( uint256 optionAllocation, uint256 newOptionAllocation ); event InstantWithdraw( address indexed account, uint256 share, uint256 round ); event PlaceAuctionBid( uint256 auctionId, address indexed auctioningToken, uint256 sellAmount, uint256 buyAmount, address indexed bidder ); /************************************************ * CONSTRUCTOR & INITIALIZATION ***********************************************/ /** * @notice Initializes the contract with immutable variables * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _gammaController is the contract address for opyn actions * @param _marginPool is the contract address for providing collateral to opyn * @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions */ constructor( address _weth, address _usdc, address _gammaController, address _marginPool, address _gnosisEasyAuction ) RibbonVault( _weth, _usdc, _gammaController, _marginPool, _gnosisEasyAuction ) {} /** * @notice Initializes the OptionVault contract with storage variables. * @param _owner is the owner of the vault with critical permissions * @param _feeRecipient is the address to recieve vault performance and management fees * @param _managementFee is the management fee pct. * @param _performanceFee is the perfomance fee pct. * @param _tokenName is the name of the token * @param _tokenSymbol is the symbol of the token * @param _counterpartyThetaVault is the address of the counterparty theta vault of this delta vault * @param _optionAllocation is the pct of the funds to allocate towards the weekly option * @param _vaultParams is the struct with vault general data */ function initialize( address _owner, address _keeper, address _feeRecipient, uint256 _managementFee, uint256 _performanceFee, string memory _tokenName, string memory _tokenSymbol, address _counterpartyThetaVault, uint256 _optionAllocation, Vault.VaultParams calldata _vaultParams ) external initializer { baseInitialize( _owner, _keeper, _feeRecipient, _managementFee, _performanceFee, _tokenName, _tokenSymbol, _vaultParams ); require( _counterpartyThetaVault != address(0), "!_counterpartyThetaVault" ); require( IRibbonThetaVault(_counterpartyThetaVault).vaultParams().asset == vaultParams.asset, "!_counterpartyThetaVault: asset" ); // 1000 = 10%. Needs to be less than 10% of the funds allocated to option. require( _optionAllocation > 0 && _optionAllocation < 10 * Vault.OPTION_ALLOCATION_MULTIPLIER, "!_optionAllocation" ); counterpartyThetaVault = IRibbonThetaVault(_counterpartyThetaVault); optionAllocation = _optionAllocation; } /** * @notice Updates the price per share of the current round. The current round * pps will change right after call rollToNextOption as the gnosis auction contract * takes custody of a % of `asset` tokens, and right after we claim the tokens from * the action as we may recieve some of `asset` tokens back alongside the oToken, * depending on the gnosis auction outcome. Finally it will change at the end of the week * if the oTokens are ITM */ function updatePPS(bool isWithdraw) internal { uint256 currentRound = vaultState.round; if ( !isWithdraw || roundPricePerShare[currentRound] <= ShareMath.PLACEHOLDER_UINT ) { roundPricePerShare[currentRound] = ShareMath.pricePerShare( totalSupply(), IERC20(vaultParams.asset).balanceOf(address(this)), vaultState.totalPending, vaultParams.decimals ); } } /************************************************ * SETTERS ***********************************************/ /** * @notice Sets the new % allocation of funds towards options purchases (2 decimals. ex: 10 * 10**2 is 10%) * 0 < newOptionAllocation < 1000. 1000 = 10%. * @param newOptionAllocation is the option % allocation */ function setOptionAllocation(uint16 newOptionAllocation) external onlyOwner { // Needs to be less than 10% require( newOptionAllocation > 0 && newOptionAllocation < 10 * Vault.OPTION_ALLOCATION_MULTIPLIER, "Invalid allocation" ); emit NewOptionAllocationSet(optionAllocation, newOptionAllocation); optionAllocation = newOptionAllocation; } /************************************************ * VAULT OPERATIONS ***********************************************/ /** * @notice Withdraws the assets on the vault using the outstanding `DepositReceipt.amount` * @param share is the amount of shares to withdraw */ function withdrawInstantly(uint256 share) external nonReentrant { require(share > 0, "!numShares"); updatePPS(true); (uint256 sharesToWithdrawFromPending, uint256 sharesLeftForWithdrawal) = _withdrawFromNewDeposit(share); // Withdraw shares from pending amount if (sharesToWithdrawFromPending > 0) { vaultState.totalPending = uint128( uint256(vaultState.totalPending).sub( sharesToWithdrawFromPending ) ); } uint256 currentRound = vaultState.round; // If we need to withdraw beyond current round deposit if (sharesLeftForWithdrawal > 0) { (uint256 heldByAccount, uint256 heldByVault) = shareBalances(msg.sender); require( sharesLeftForWithdrawal <= heldByAccount.add(heldByVault), "Insufficient balance" ); if (heldByAccount < sharesLeftForWithdrawal) { // Redeem all shares custodied by vault to user _redeem(0, true); } // Burn shares _burn(msg.sender, sharesLeftForWithdrawal); } emit InstantWithdraw(msg.sender, share, currentRound); uint256 withdrawAmount = ShareMath.sharesToAsset( share, roundPricePerShare[currentRound], vaultParams.decimals ); transferAsset(msg.sender, withdrawAmount); } /** * @notice Closes the existing long position for the vault. * This allows all the users to withdraw if the next option is malicious. */ function commitAndClose() external nonReentrant { address oldOption = optionState.currentOption; address counterpartyNextOption = counterpartyThetaVault.optionState().nextOption; require(counterpartyNextOption != address(0), "!thetavaultclosed"); updatePPS(true); optionState.nextOption = counterpartyNextOption; uint256 nextOptionReady = block.timestamp.add(DELAY); require( nextOptionReady <= type(uint32).max, "Overflow nextOptionReady" ); optionState.nextOptionReadyAt = uint32(nextOptionReady); optionState.currentOption = address(0); vaultState.lastLockedAmount = uint104(balanceBeforePremium); // redeem if (oldOption != address(0)) { uint256 profitAmount = VaultLifecycle.settleLong( GAMMA_CONTROLLER, oldOption, vaultParams.asset ); emit CloseLong(oldOption, profitAmount, msg.sender); } } /** * @notice Rolls the vault's funds into a new long position. * @param optionPremium is the premium per token to pay in `asset`. Same decimals as `asset` (ex: 1 * 10 ** 8 means 1 WBTC per oToken) */ function rollToNextOption(uint256 optionPremium) external onlyKeeper nonReentrant { (address newOption, uint256 lockedBalance) = _rollToNextOption(); balanceBeforePremium = lockedBalance; GnosisAuction.BidDetails memory bidDetails; bidDetails.auctionId = counterpartyThetaVault.optionAuctionID(); bidDetails.gnosisEasyAuction = GNOSIS_EASY_AUCTION; bidDetails.oTokenAddress = newOption; bidDetails.asset = vaultParams.asset; bidDetails.assetDecimals = vaultParams.decimals; bidDetails.lockedBalance = lockedBalance; bidDetails.optionAllocation = optionAllocation; bidDetails.optionPremium = optionPremium; bidDetails.bidder = msg.sender; // place bid (uint256 sellAmount, uint256 buyAmount, uint64 userId) = VaultLifecycle.placeBid(bidDetails); auctionSellOrder.sellAmount = uint96(sellAmount); auctionSellOrder.buyAmount = uint96(buyAmount); auctionSellOrder.userId = userId; updatePPS(false); emit OpenLong(newOption, buyAmount, sellAmount, msg.sender); } /** * @notice Claims the delta vault's oTokens from latest auction */ function claimAuctionOtokens() external nonReentrant { VaultLifecycle.claimAuctionOtokens( auctionSellOrder, GNOSIS_EASY_AUCTION, address(counterpartyThetaVault) ); updatePPS(false); } /** * @notice Withdraws from the most recent deposit which has not been processed * @param share is how many shares to withdraw in total * @return the shares to remove from pending * @return the shares left to withdraw */ function _withdrawFromNewDeposit(uint256 share) private returns (uint256, uint256) { Vault.DepositReceipt storage depositReceipt = depositReceipts[msg.sender]; // Immediately get what is in the pending deposits, without need for checking pps if ( depositReceipt.round == vaultState.round && depositReceipt.amount > 0 ) { uint256 receiptShares = ShareMath.assetToShares( depositReceipt.amount, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 sharesWithdrawn = Math.min(receiptShares, share); // Subtraction underflow checks already ensure it is smaller than uint104 depositReceipt.amount = uint104( ShareMath.sharesToAsset( uint256(receiptShares).sub(sharesWithdrawn), roundPricePerShare[depositReceipt.round], vaultParams.decimals ) ); return (sharesWithdrawn, share.sub(sharesWithdrawn)); } return (0, share); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {DSMath} from "../vendor/DSMath.sol"; import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol"; import {IOtoken} from "../interfaces/GammaInterface.sol"; import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol"; import {Vault} from "./Vault.sol"; import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol"; library GnosisAuction { using SafeMath for uint256; using SafeERC20 for IERC20; event InitiateGnosisAuction( address indexed auctioningToken, address indexed biddingToken, uint256 auctionCounter, address indexed manager ); event PlaceAuctionBid( uint256 auctionId, address indexed auctioningToken, uint256 sellAmount, uint256 buyAmount, address indexed bidder ); struct AuctionDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 oTokenPremium; uint256 duration; } struct BidDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 auctionId; uint256 lockedBalance; uint256 optionAllocation; uint256 optionPremium; address bidder; } function startAuction(AuctionDetails calldata auctionDetails) internal returns (uint256 auctionID) { uint256 oTokenSellAmount = getOTokenSellAmount(auctionDetails.oTokenAddress); IERC20(auctionDetails.oTokenAddress).safeApprove( auctionDetails.gnosisEasyAuction, IERC20(auctionDetails.oTokenAddress).balanceOf(address(this)) ); // minBidAmount is total oTokens to sell * premium per oToken // shift decimals to correspond to decimals of USDC for puts // and underlying for calls uint256 minBidAmount = DSMath .wmul( oTokenSellAmount.mul(10**10), auctionDetails .oTokenPremium ) .div(10**(uint256(18).sub(auctionDetails.assetDecimals))); require( minBidAmount <= type(uint96).max, "optionPremium * oTokenSellAmount > type(uint96) max value!" ); uint256 auctionEnd = block.timestamp.add(auctionDetails.duration); auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction) .initiateAuction( // address of oToken we minted and are selling auctionDetails.oTokenAddress, // address of asset we want in exchange for oTokens. Should match vault `asset` auctionDetails.asset, // orders can be cancelled at any time during the auction auctionEnd, // order will last for `duration` auctionEnd, // we are selling all of the otokens minus a fee taken by gnosis uint96(oTokenSellAmount), // the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price uint96(minBidAmount), // the minimum bidding amount must be 1 * 10 ** -assetDecimals 1, // the min funding threshold 0, // no atomic closure false, // access manager contract address(0), // bytes for storing info like a whitelist for who can bid bytes("") ); emit InitiateGnosisAuction( auctionDetails.oTokenAddress, auctionDetails.asset, auctionID, msg.sender ); } function placeBid(BidDetails calldata bidDetails) internal returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { // calculate how much to allocate sellAmount = bidDetails .lockedBalance .mul(bidDetails.optionAllocation) .div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER); // divide the `asset` sellAmount by the target premium per oToken to // get the number of oTokens to buy (8 decimals) buyAmount = sellAmount .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS))) .div(bidDetails.optionPremium) .div(10**bidDetails.assetDecimals); require( sellAmount <= type(uint96).max, "sellAmount > type(uint96) max value!" ); require( buyAmount <= type(uint96).max, "buyAmount > type(uint96) max value!" ); // approve that amount IERC20(bidDetails.asset).safeApprove( bidDetails.gnosisEasyAuction, sellAmount ); uint96[] memory _minBuyAmounts = new uint96[](1); uint96[] memory _sellAmounts = new uint96[](1); bytes32[] memory _prevSellOrders = new bytes32[](1); _minBuyAmounts[0] = uint96(buyAmount); _sellAmounts[0] = uint96(sellAmount); _prevSellOrders[ 0 ] = 0x0000000000000000000000000000000000000000000000000000000000000001; // place sell order with that amount userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders( bidDetails.auctionId, _minBuyAmounts, _sellAmounts, _prevSellOrders, "0x" ); emit PlaceAuctionBid( bidDetails.auctionId, bidDetails.oTokenAddress, sellAmount, buyAmount, bidDetails.bidder ); return (sellAmount, buyAmount, userId); } function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) internal { bytes32 order = encodeOrder( auctionSellOrder.userId, auctionSellOrder.buyAmount, auctionSellOrder.sellAmount ); bytes32[] memory orders = new bytes32[](1); orders[0] = order; IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder( IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(), orders ); } function getOTokenSellAmount(address oTokenAddress) internal view returns (uint256) { // We take our current oToken balance. That will be our sell amount // but otokens will be transferred to gnosis. uint256 oTokenSellAmount = IERC20(oTokenAddress).balanceOf(address(this)); require( oTokenSellAmount <= type(uint96).max, "oTokenSellAmount > type(uint96) max value!" ); return oTokenSellAmount; } function getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount ) internal view returns (uint256) { IOtoken newOToken = IOtoken(oTokenAddress); IOptionsPremiumPricer premiumPricer = IOptionsPremiumPricer(optionsPremiumPricer); // Apply black-scholes formula (from rvol library) to option given its features // and get price for 100 contracts denominated in the underlying asset for call option // and USDC for put option uint256 optionPremium = premiumPricer.getPremium( newOToken.strikePrice(), newOToken.expiryTimestamp(), newOToken.isPut() ); // Apply a discount to incentivize arbitraguers optionPremium = optionPremium.mul(premiumDiscount).div( 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER ); require( optionPremium <= type(uint96).max, "optionPremium > type(uint96) max value!" ); return optionPremium; } function encodeOrder( uint64 userId, uint96 buyAmount, uint96 sellAmount ) internal pure returns (bytes32) { return bytes32( (uint256(userId) << 192) + (uint256(buyAmount) << 96) + uint256(sellAmount) ); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol"; import {Vault} from "../libraries/Vault.sol"; abstract contract RibbonDeltaVaultStorageV1 { // Ribbon counterparty theta vault IRibbonThetaVault public counterpartyThetaVault; // % of funds to be used for weekly option purchase uint256 public optionAllocation; // Delta vault equivalent of lockedAmount uint256 public balanceBeforePremium; // User Id of delta vault in latest gnosis auction Vault.AuctionSellOrder public auctionSellOrder; } // We are following Compound's method of upgrading new contract implementations // When we need to add new storage variables, we create a new version of RibbonDeltaVaultStorage // e.g. RibbonDeltaVaultStorage<versionNumber>, so finally it would look like // contract RibbonDeltaVaultStorage is RibbonDeltaVaultStorageV1, RibbonDeltaVaultStorageV2 abstract contract RibbonDeltaVaultStorage is RibbonDeltaVaultStorageV1 { } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library Vault { /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ // Fees are 6-decimal places. For example: 20 * 10**6 = 20% uint256 internal constant FEE_MULTIPLIER = 10**6; // Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount. uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10; // Otokens have 8 decimal places. uint256 internal constant OTOKEN_DECIMALS = 8; // Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10% uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2; // Placeholder uint value to prevent cold writes uint256 internal constant PLACEHOLDER_UINT = 1; struct VaultParams { // Option type the vault is selling bool isPut; // Token decimals for vault shares uint8 decimals; // Asset used in Theta / Delta Vault address asset; // Underlying asset of the options sold by vault address underlying; // Minimum supply of the vault shares issued, for ETH it's 10**10 uint56 minimumSupply; // Vault cap uint104 cap; } struct OptionState { // Option that the vault is shorting / longing in the next cycle address nextOption; // Option that the vault is currently shorting / longing address currentOption; // The timestamp when the `nextOption` can be used by the vault uint32 nextOptionReadyAt; } struct VaultState { // 32 byte slot 1 // Current round number. `round` represents the number of `period`s elapsed. uint16 round; // Amount that is currently locked for selling options uint104 lockedAmount; // Amount that was locked for selling options in the previous round // used for calculating performance fee deduction uint104 lastLockedAmount; // 32 byte slot 2 // Stores the total tally of how much of `asset` there is // to be used to mint rTHETA tokens uint128 totalPending; // Amount locked for scheduled withdrawals; uint128 queuedWithdrawShares; } struct DepositReceipt { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit uint104 amount; // Unredeemed shares balance uint128 unredeemedShares; } struct Withdrawal { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Number of shares withdrawn uint128 shares; } struct AuctionSellOrder { // Amount of `asset` token offered in auction uint96 sellAmount; // Amount of oToken requested in auction uint96 buyAmount; // User Id of delta vault in latest gnosis auction uint64 userId; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Vault} from "./Vault.sol"; import {ShareMath} from "./ShareMath.sol"; import {IStrikeSelection} from "../interfaces/IRibbon.sol"; import {GnosisAuction} from "./GnosisAuction.sol"; import { IOtokenFactory, IOtoken, IController, GammaTypes } from "../interfaces/GammaInterface.sol"; import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol"; import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol"; library VaultLifecycle { using SafeMath for uint256; using SupportsNonCompliantERC20 for IERC20; struct CloseParams { address OTOKEN_FACTORY; address USDC; address currentOption; uint256 delay; uint16 lastStrikeOverrideRound; uint256 overriddenStrikePrice; } /** * @notice Sets the next option the vault will be shorting, and calculates its premium for the auction * @param strikeSelection is the address of the contract with strike selection logic * @param optionsPremiumPricer is the address of the contract with the black-scholes premium calculation logic * @param premiumDiscount is the vault's discount applied to the premium * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param vaultState is the struct with vault accounting state * @return otokenAddress is the address of the new option * @return premium is the premium of the new option * @return strikePrice is the strike price of the new option * @return delta is the delta of the new option */ function commitAndClose( address strikeSelection, address optionsPremiumPricer, uint256 premiumDiscount, CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, Vault.VaultState storage vaultState ) external returns ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) { uint256 expiry; // uninitialized state if (closeParams.currentOption == address(0)) { expiry = getNextFriday(block.timestamp); } else { expiry = getNextFriday( IOtoken(closeParams.currentOption).expiryTimestamp() ); } IStrikeSelection selection = IStrikeSelection(strikeSelection); bool isPut = vaultParams.isPut; address underlying = vaultParams.underlying; address asset = vaultParams.asset; (strikePrice, delta) = closeParams.lastStrikeOverrideRound == vaultState.round ? (closeParams.overriddenStrikePrice, selection.delta()) : selection.getStrikePrice(expiry, isPut); require(strikePrice != 0, "!strikePrice"); // retrieve address if option already exists, or deploy it otokenAddress = getOrDeployOtoken( closeParams, vaultParams, underlying, asset, strikePrice, expiry, isPut ); // get the black scholes premium of the option premium = GnosisAuction.getOTokenPremium( otokenAddress, optionsPremiumPricer, premiumDiscount ); require(premium > 0, "!premium"); return (otokenAddress, premium, strikePrice, delta); } /** * @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes * @param otokenAddress is the address of the otoken * @param vaultParams is the struct with vault general data * @param collateralAsset is the address of the collateral asset * @param USDC is the address of usdc * @param delay is the delay between commitAndClose and rollToNextOption */ function verifyOtoken( address otokenAddress, Vault.VaultParams storage vaultParams, address collateralAsset, address USDC, uint256 delay ) private view { require(otokenAddress != address(0), "!otokenAddress"); IOtoken otoken = IOtoken(otokenAddress); require(otoken.isPut() == vaultParams.isPut, "Type mismatch"); require( otoken.underlyingAsset() == vaultParams.underlying, "Wrong underlyingAsset" ); require( otoken.collateralAsset() == collateralAsset, "Wrong collateralAsset" ); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay"); } /** * @notice Calculate the shares to mint, new price per share, and amount of funds to re-allocate as collateral for the new round * @param currentShareSupply is the total supply of shares * @param asset is the address of the vault's asset * @param decimals is the decimals of the asset * @param pendingAmount is the amount of funds pending from recent deposits * @return newLockedAmount is the amount of funds to allocate for the new round * @return queuedWithdrawAmount is the amount of funds set aside for withdrawal * @return newPricePerShare is the price per share of the new round * @return mintShares is the amount of shares to mint from deposits */ function rollover( uint256 currentShareSupply, address asset, uint256 decimals, uint256 pendingAmount, uint256 queuedWithdrawShares ) external view returns ( uint256 newLockedAmount, uint256 queuedWithdrawAmount, uint256 newPricePerShare, uint256 mintShares ) { uint256 currentBalance = IERC20(asset).balanceOf(address(this)); newPricePerShare = ShareMath.pricePerShare( currentShareSupply, currentBalance, pendingAmount, decimals ); // After closing the short, if the options expire in-the-money // vault pricePerShare would go down because vault's asset balance decreased. // This ensures that the newly-minted shares do not take on the loss. uint256 _mintShares = ShareMath.assetToShares(pendingAmount, newPricePerShare, decimals); uint256 newSupply = currentShareSupply.add(_mintShares); uint256 queuedWithdraw = newSupply > 0 ? ShareMath.sharesToAsset( queuedWithdrawShares, newPricePerShare, decimals ) : 0; return ( currentBalance.sub(queuedWithdraw), queuedWithdraw, newPricePerShare, _mintShares ); } /** * @notice Creates the actual Opyn short position by depositing collateral and minting otokens * @param gammaController is the address of the opyn controller contract * @param marginPool is the address of the opyn margin contract which holds the collateral * @param oTokenAddress is the address of the otoken to mint * @param depositAmount is the amount of collateral to deposit * @return the otoken mint amount */ function createShort( address gammaController, address marginPool, address oTokenAddress, uint256 depositAmount ) external returns (uint256) { IController controller = IController(gammaController); uint256 newVaultID = (controller.getAccountVaultCounter(address(this))).add(1); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IOtoken oToken = IOtoken(oTokenAddress); address collateralAsset = oToken.collateralAsset(); uint256 collateralDecimals = uint256(IERC20Detailed(collateralAsset).decimals()); uint256 mintAmount; if (oToken.isPut()) { // For minting puts, there will be instances where the full depositAmount will not be used for minting. // This is because of an issue with precision. // // For ETH put options, we are calculating the mintAmount (10**8 decimals) using // the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down. // As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens. // // For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens. // We retain the dust in the vault so the calling contract can withdraw the // actual locked amount + dust at settlement. // // To test this behavior, we can console.log // MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault) // to see how much dust (or excess collateral) is left behind. mintAmount = depositAmount .mul(10**Vault.OTOKEN_DECIMALS) .mul(10**18) // we use 10**18 to give extra precision .div(oToken.strikePrice().mul(10**(10 + collateralDecimals))); } else { mintAmount = depositAmount; uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals if (mintAmount > scaleBy && collateralDecimals > 8) { mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8 } } // double approve to fix non-compliant ERC20s IERC20 collateralToken = IERC20(collateralAsset); collateralToken.safeApproveNonCompliant(marginPool, depositAmount); IController.ActionArgs[] memory actions = new IController.ActionArgs[](3); actions[0] = IController.ActionArgs( IController.ActionType.OpenVault, address(this), // owner address(this), // receiver address(0), // asset, otoken newVaultID, // vaultId 0, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.DepositCollateral, address(this), // owner address(this), // address to transfer from collateralAsset, // deposited asset newVaultID, // vaultId depositAmount, // amount 0, //index "" //data ); actions[2] = IController.ActionArgs( IController.ActionType.MintShortOption, address(this), // owner address(this), // address to transfer to oTokenAddress, // deposited asset newVaultID, // vaultId mintAmount, // amount 0, //index "" //data ); controller.operate(actions); return mintAmount; } /** * @notice Close the existing short otoken position. Currently this implementation is simple. * It closes the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by calling SettleVault action, this assumption should hold. * @param gammaController is the address of the opyn controller contract * @return amount of collateral redeemed from the vault */ function settleShort(address gammaController) external returns (uint256) { IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IERC20 collateralToken = IERC20(vault.collateralAssets[0]); // The short position has been previously closed, or all the otokens have been burned. // So we return early. if (address(collateralToken) == address(0)) { return 0; } // This is equivalent to doing IERC20(vault.asset).balanceOf(address(this)) uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // If it is after expiry, we need to settle the short position using the normal way // Delete the vault and withdraw all remaining collateral from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.SettleVault, address(this), // owner address(this), // address to transfer to address(0), // not used vaultID, // vaultId 0, // not used 0, // not used "" // not used ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple. * It calls the `Redeem` action to claim the payout. * @param gammaController is the address of the opyn controller contract * @param oldOption is the address of the old option * @param asset is the address of the vault's asset * @return amount of asset received by exercising the option */ function settleLong( address gammaController, address oldOption, address asset ) external returns (uint256) { IController controller = IController(gammaController); uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this)); if (controller.getPayout(oldOption, oldOptionBalance) == 0) { return 0; } uint256 startAssetBalance = IERC20(asset).balanceOf(address(this)); // If it is after expiry, we need to redeem the profits IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.Redeem, address(0), // not used address(this), // address to send profits to oldOption, // address of otoken 0, // not used oldOptionBalance, // otoken balance 0, // not used "" // not used ); controller.operate(actions); uint256 endAssetBalance = IERC20(asset).balanceOf(address(this)); return endAssetBalance.sub(startAssetBalance); } /** * @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple. * It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. * @param gammaController is the address of the opyn controller contract * @param currentOption is the address of the current option * @return amount of collateral redeemed by burning otokens */ function burnOtokens(address gammaController, address currentOption) external returns (uint256) { uint256 numOTokensToBurn = IERC20(currentOption).balanceOf(address(this)); require(numOTokensToBurn > 0, "No oTokens to burn"); IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); IERC20 collateralToken = IERC20(vault.collateralAssets[0]); uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // Burning `amount` of oTokens from the ribbon vault, // then withdrawing the corresponding collateral amount from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](2); actions[0] = IController.ActionArgs( IController.ActionType.BurnShortOption, address(this), // owner address(this), // address to transfer from address(vault.shortOtokens[0]), // otoken address vaultID, // vaultId numOTokensToBurn, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.WithdrawCollateral, address(this), // owner address(this), // address to transfer to address(collateralToken), // withdrawn asset vaultID, // vaultId vault.collateralAmounts[0].mul(numOTokensToBurn).div( vault.shortAmounts[0] ), // amount 0, //index "" //data ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Calculates the performance and management fee for this week's round * @param vaultState is the struct with vault accounting state * @param currentLockedBalance is the amount of funds currently locked in opyn * @param performanceFeePercent is the performance fee pct. * @param managementFeePercent is the management fee pct. * @return performanceFeeInAsset is the performance fee * @return managementFeeInAsset is the management fee * @return vaultFee is the total fees */ function getVaultFees( Vault.VaultState storage vaultState, uint256 currentLockedBalance, uint256 performanceFeePercent, uint256 managementFeePercent ) external view returns ( uint256 performanceFeeInAsset, uint256 managementFeeInAsset, uint256 vaultFee ) { uint256 prevLockedAmount = vaultState.lastLockedAmount; uint256 lockedBalanceSansPending = currentLockedBalance.sub(vaultState.totalPending); uint256 _performanceFeeInAsset; uint256 _managementFeeInAsset; uint256 _vaultFee; // Take performance fee and management fee ONLY if difference between // last week and this week's vault deposits, taking into account pending // deposits and withdrawals, is positive. If it is negative, last week's // option expired ITM past breakeven, and the vault took a loss so we // do not collect performance fee for last week if (lockedBalanceSansPending > prevLockedAmount) { _performanceFeeInAsset = performanceFeePercent > 0 ? lockedBalanceSansPending .sub(prevLockedAmount) .mul(performanceFeePercent) .div(100 * Vault.FEE_MULTIPLIER) : 0; _managementFeeInAsset = managementFeePercent > 0 ? lockedBalanceSansPending.mul(managementFeePercent).div( 100 * Vault.FEE_MULTIPLIER ) : 0; _vaultFee = _performanceFeeInAsset.add(_managementFeeInAsset); } return (_performanceFeeInAsset, _managementFeeInAsset, _vaultFee); } /** * @notice Either retrieves the option token if it already exists, or deploy it * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param underlying is the address of the underlying asset of the option * @param collateralAsset is the address of the collateral asset of the option * @param strikePrice is the strike price of the option * @param expiry is the expiry timestamp of the option * @param isPut is whether the option is a put * @return the address of the option */ function getOrDeployOtoken( CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, address underlying, address collateralAsset, uint256 strikePrice, uint256 expiry, bool isPut ) internal returns (address) { IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY); address otokenFromFactory = factory.getOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); if (otokenFromFactory != address(0)) { return otokenFromFactory; } address otoken = factory.createOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); verifyOtoken( otoken, vaultParams, collateralAsset, closeParams.USDC, closeParams.delay ); return otoken; } /** * @notice Starts the gnosis auction * @param auctionDetails is the struct with all the custom parameters of the auction * @return the auction id of the newly created auction */ function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails) external returns (uint256) { return GnosisAuction.startAuction(auctionDetails); } /** * @notice Places a bid in an auction * @param bidDetails is the struct with all the details of the bid including the auction's id and how much to bid */ function placeBid(GnosisAuction.BidDetails calldata bidDetails) external returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { return GnosisAuction.placeBid(bidDetails); } /** * @notice Claims the oTokens belonging to the vault * @param auctionSellOrder is the sell order of the bid * @param gnosisEasyAuction is the address of the gnosis auction contract holding custody to the funds * @param counterpartyThetaVault is the address of the counterparty theta vault of this delta vault */ function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) external { GnosisAuction.claimAuctionOtokens( auctionSellOrder, gnosisEasyAuction, counterpartyThetaVault ); } /** * @notice Verify the constructor params satisfy requirements * @param owner is the owner of the vault with critical permissions * @param feeRecipient is the address to recieve vault performance and management fees * @param performanceFee is the perfomance fee pct. * @param tokenName is the name of the token * @param tokenSymbol is the symbol of the token * @param _vaultParams is the struct with vault general data */ function verifyInitializerParams( address owner, address keeper, address feeRecipient, uint256 performanceFee, uint256 managementFee, string calldata tokenName, string calldata tokenSymbol, Vault.VaultParams calldata _vaultParams ) external pure { require(owner != address(0), "!owner"); require(keeper != address(0), "!keeper"); require(feeRecipient != address(0), "!feeRecipient"); require( performanceFee < 100 * Vault.FEE_MULTIPLIER, "performanceFee >= 100%" ); require( managementFee < 100 * Vault.FEE_MULTIPLIER, "managementFee >= 100%" ); require(bytes(tokenName).length > 0, "!tokenName"); require(bytes(tokenSymbol).length > 0, "!tokenSymbol"); require(_vaultParams.asset != address(0), "!asset"); require(_vaultParams.underlying != address(0), "!underlying"); require(_vaultParams.minimumSupply > 0, "!minimumSupply"); require(_vaultParams.cap > 0, "!cap"); require( _vaultParams.cap > _vaultParams.minimumSupply, "cap has to be higher than minimumSupply" ); } /** * @notice Gets the next options expiry timestamp * @param currentExpiry is the expiry timestamp of the current option * Reference: https://codereview.stackexchange.com/a/33532 * Examples: * getNextFriday(week 1 thursday) -> week 1 friday * getNextFriday(week 1 friday) -> week 2 friday * getNextFriday(week 1 saturday) -> week 2 friday */ function getNextFriday(uint256 currentExpiry) internal pure returns (uint256) { // dayOfWeek = 0 (sunday) - 6 (saturday) uint256 dayOfWeek = ((currentExpiry / 1 days) + 4) % 7; uint256 nextFriday = currentExpiry + ((7 + 5 - dayOfWeek) % 7) * 1 days; uint256 friday8am = nextFriday - (nextFriday % (24 hours)) + (8 hours); // If the passed currentExpiry is day=Friday hour>8am, we simply increment it by a week to next Friday if (currentExpiry >= friday8am) { friday8am += 7 days; } return friday8am; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {Vault} from "./Vault.sol"; library ShareMath { using SafeMath for uint256; uint256 internal constant PLACEHOLDER_UINT = 1; function assetToShares( uint256 assetAmount, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return assetAmount.mul(10**decimals).div(assetPerShare); } function sharesToAsset( uint256 shares, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return shares.mul(assetPerShare).div(10**decimals); } /** * @notice Returns the shares unredeemed by the user given their DepositReceipt * @param depositReceipt is the user's deposit receipt * @param currentRound is the `round` stored on the vault * @param assetPerShare is the price in asset per share * @param decimals is the number of decimals the asset/shares use * @return unredeemedShares is the user's virtual balance of shares that are owed */ function getSharesFromReceipt( Vault.DepositReceipt memory depositReceipt, uint256 currentRound, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256 unredeemedShares) { if (depositReceipt.round > 0 && depositReceipt.round < currentRound) { uint256 sharesFromRound = assetToShares(depositReceipt.amount, assetPerShare, decimals); return uint256(depositReceipt.unredeemedShares).add(sharesFromRound); } return depositReceipt.unredeemedShares; } function pricePerShare( uint256 totalSupply, uint256 totalBalance, uint256 pendingAmount, uint256 decimals ) internal pure returns (uint256) { uint256 singleShare = 10**decimals; return totalSupply > 0 ? singleShare.mul(totalBalance.sub(pendingAmount)).div( totalSupply ) : singleShare; } /************************************************ * HELPERS ***********************************************/ function assertUint104(uint256 num) internal pure { require(num <= type(uint104).max, "Overflow uint104"); } function assertUint128(uint256 num) internal pure { require(num <= type(uint128).max, "Overflow uint128"); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {Vault} from "../../../libraries/Vault.sol"; import {VaultLifecycle} from "../../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../../libraries/ShareMath.sol"; import {IWETH} from "../../../interfaces/IWETH.sol"; contract RibbonVault is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; /************************************************ * NON UPGRADEABLE STORAGE ***********************************************/ /// @notice Stores the user's pending deposit for the round mapping(address => Vault.DepositReceipt) public depositReceipts; /// @notice On every round's close, the pricePerShare value of an rTHETA token is stored /// This is used to determine the number of shares to be returned /// to a user with their DepositReceipt.depositAmount mapping(uint256 => uint256) public roundPricePerShare; /// @notice Stores pending user withdrawals mapping(address => Vault.Withdrawal) public withdrawals; /// @notice Vault's parameters like cap, decimals Vault.VaultParams public vaultParams; /// @notice Vault's lifecycle state like round and locked amounts Vault.VaultState public vaultState; /// @notice Vault's state of the options sold and the timelocked option Vault.OptionState public optionState; /// @notice Fee recipient for the performance and management fees address public feeRecipient; /// @notice role in charge of weekly vault operations such as rollToNextOption and burnRemainingOTokens // no access to critical vault changes address public keeper; /// @notice Performance fee charged on premiums earned in rollToNextOption. Only charged when there is no loss. uint256 public performanceFee; /// @notice Management fee charged on entire AUM in rollToNextOption. Only charged when there is no loss. uint256 public managementFee; // Gap is left to avoid storage collisions. Though RibbonVault is not upgradeable, we add this as a safety measure. uint256[30] private ____gap; // *IMPORTANT* NO NEW STORAGE VARIABLES SHOULD BE ADDED HERE // This is to prevent storage collisions. All storage variables should be appended to RibbonThetaVaultStorage // or RibbonDeltaVaultStorage instead. Read this documentation to learn more: // https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice WETH9 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 address public immutable WETH; /// @notice USDC 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 address public immutable USDC; /// @notice 15 minute timelock between commitAndClose and rollToNexOption. uint256 public constant DELAY = 15 minutes; /// @notice 7 day period between each options sale. uint256 public constant PERIOD = 7 days; // Number of weeks per year = 52.142857 weeks * FEE_MULTIPLIER = 52142857 // Dividing by weeks per year requires doing num.mul(FEE_MULTIPLIER).div(WEEKS_PER_YEAR) uint256 private constant WEEKS_PER_YEAR = 52142857; // GAMMA_CONTROLLER is the top-level contract in Gamma protocol // which allows users to perform multiple actions on their vaults // and positions https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/Controller.sol address public immutable GAMMA_CONTROLLER; // MARGIN_POOL is Gamma protocol's collateral pool. // Needed to approve collateral.safeTransferFrom for minting otokens. // https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/MarginPool.sol address public immutable MARGIN_POOL; // GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids // https://github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol address public immutable GNOSIS_EASY_AUCTION; /************************************************ * EVENTS ***********************************************/ event Deposit(address indexed account, uint256 amount, uint256 round); event InitiateWithdraw( address indexed account, uint256 shares, uint256 round ); event Redeem(address indexed account, uint256 share, uint256 round); event ManagementFeeSet(uint256 managementFee, uint256 newManagementFee); event PerformanceFeeSet(uint256 performanceFee, uint256 newPerformanceFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); event Withdraw(address indexed account, uint256 amount, uint256 shares); event CollectVaultFees( uint256 performanceFee, uint256 vaultFee, uint256 round, address indexed feeRecipient ); /************************************************ * CONSTRUCTOR & INITIALIZATION ***********************************************/ /** * @notice Initializes the contract with immutable variables * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _gammaController is the contract address for opyn actions * @param _marginPool is the contract address for providing collateral to opyn * @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions */ constructor( address _weth, address _usdc, address _gammaController, address _marginPool, address _gnosisEasyAuction ) { require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_gnosisEasyAuction != address(0), "!_gnosisEasyAuction"); require(_gammaController != address(0), "!_gammaController"); require(_marginPool != address(0), "!_marginPool"); WETH = _weth; USDC = _usdc; GAMMA_CONTROLLER = _gammaController; MARGIN_POOL = _marginPool; GNOSIS_EASY_AUCTION = _gnosisEasyAuction; } /** * @notice Initializes the OptionVault contract with storage variables. */ function baseInitialize( address _owner, address _keeper, address _feeRecipient, uint256 _managementFee, uint256 _performanceFee, string memory _tokenName, string memory _tokenSymbol, Vault.VaultParams calldata _vaultParams ) internal initializer { VaultLifecycle.verifyInitializerParams( _owner, _keeper, _feeRecipient, _performanceFee, _managementFee, _tokenName, _tokenSymbol, _vaultParams ); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); keeper = _keeper; feeRecipient = _feeRecipient; performanceFee = _performanceFee; managementFee = _managementFee.mul(Vault.FEE_MULTIPLIER).div( WEEKS_PER_YEAR ); vaultParams = _vaultParams; uint256 assetBalance = IERC20(vaultParams.asset).balanceOf(address(this)); ShareMath.assertUint104(assetBalance); vaultState.lastLockedAmount = uint104(assetBalance); vaultState.round = 1; } /** * @dev Throws if called by any account other than the keeper. */ modifier onlyKeeper() { require(msg.sender == keeper, "!keeper"); _; } /************************************************ * SETTERS ***********************************************/ /** * @notice Sets the new keeper * @param newKeeper is the address of the new keeper */ function setNewKeeper(address newKeeper) external onlyOwner { require(newKeeper != address(0), "!newKeeper"); keeper = newKeeper; } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); require(newFeeRecipient != feeRecipient, "Must be new feeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the management fee for the vault * @param newManagementFee is the management fee (6 decimals). ex: 2 * 10 ** 6 = 2% */ function setManagementFee(uint256 newManagementFee) external onlyOwner { require( newManagementFee < 100 * Vault.FEE_MULTIPLIER, "Invalid management fee" ); // We are dividing annualized management fee by num weeks in a year managementFee = newManagementFee.mul(Vault.FEE_MULTIPLIER).div( WEEKS_PER_YEAR ); } /** * @notice Sets the performance fee for the vault * @param newPerformanceFee is the performance fee (6 decimals). ex: 20 * 10 ** 6 = 20% */ function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner { require( newPerformanceFee < 100 * Vault.FEE_MULTIPLIER, "Invalid performance fee" ); emit PerformanceFeeSet(performanceFee, newPerformanceFee); performanceFee = newPerformanceFee; } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyOwner { require(newCap > 0, "!newCap"); ShareMath.assertUint104(newCap); vaultParams.cap = uint104(newCap); } /************************************************ * DEPOSIT & WITHDRAWALS ***********************************************/ /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the asset is not WETH. */ function depositETH() external payable nonReentrant { require(vaultParams.asset == WETH, "!WETH"); require(msg.value > 0, "!value"); _depositFor(msg.value, msg.sender); IWETH(WETH).deposit{value: msg.value}(); } /** * @notice Deposits the `asset` from msg.sender. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { require(amount > 0, "!amount"); _depositFor(amount, msg.sender); // An approve() by the msg.sender is required beforehand IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } /** * @notice Deposits the `asset` from msg.sender added to `creditor`'s deposit. * @notice Used for vault -> vault deposits on the user's behalf * @param amount is the amount of `asset` to deposit * @param creditor is the address that can claim/withdraw deposited amount */ function depositFor(uint256 amount, address creditor) external nonReentrant { require(amount > 0, "!amount"); require(creditor != address(0)); _depositFor(amount, creditor); // An approve() by the msg.sender is required beforehand IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } /** * @notice Mints the vault shares to the creditor * @param amount is the amount of `asset` deposited * @param creditor is the address to receieve the deposit */ function _depositFor(uint256 amount, address creditor) private { uint256 currentRound = vaultState.round; uint256 totalWithDepositedAmount = totalBalance().add(amount); require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap"); require( totalWithDepositedAmount >= vaultParams.minimumSupply, "Insufficient balance" ); emit Deposit(creditor, amount, currentRound); Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor]; // If we have an unprocessed pending deposit from the previous rounds, we have to process it. uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount; // If we have a pending deposit in the current round, we add on to the pending deposit if (currentRound == depositReceipt.round) { uint256 newAmount = uint256(depositReceipt.amount).add(amount); depositAmount = newAmount; } ShareMath.assertUint104(depositAmount); depositReceipts[creditor] = Vault.DepositReceipt({ round: uint16(currentRound), amount: uint104(depositAmount), unredeemedShares: uint128(unredeemedShares) }); uint256 newTotalPending = uint256(vaultState.totalPending).add(amount); ShareMath.assertUint128(newTotalPending); vaultState.totalPending = uint128(newTotalPending); } /** * @notice Initiates a withdrawal that can be processed once the round completes * @param numShares is the number of shares to withdraw */ function initiateWithdraw(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); // We do a max redeem before initiating a withdrawal // But we check if they must first have unredeemed shares if ( depositReceipts[msg.sender].amount > 0 || depositReceipts[msg.sender].unredeemedShares > 0 ) { _redeem(0, true); } // This caches the `round` variable used in shareBalances uint256 currentRound = vaultState.round; Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares; if (withdrawalIsSameRound) { withdrawalShares = existingShares.add(numShares); } else { require(existingShares == 0, "Existing withdraw"); withdrawalShares = numShares; withdrawals[msg.sender].round = uint16(currentRound); } ShareMath.assertUint128(withdrawalShares); withdrawals[msg.sender].shares = uint128(withdrawalShares); uint256 newQueuedWithdrawShares = uint256(vaultState.queuedWithdrawShares).add(numShares); ShareMath.assertUint128(newQueuedWithdrawShares); vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares); _transfer(msg.sender, address(this), numShares); } /** * @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round */ function completeWithdraw() external nonReentrant { Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; uint256 withdrawalShares = withdrawal.shares; uint256 withdrawalRound = withdrawal.round; // This checks if there is a withdrawal require(withdrawalShares > 0, "Not initiated"); require(withdrawalRound < vaultState.round, "Round not closed"); // We leave the round number as non-zero to save on gas for subsequent writes withdrawals[msg.sender].shares = 0; vaultState.queuedWithdrawShares = uint128( uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares) ); uint256 withdrawAmount = ShareMath.sharesToAsset( withdrawalShares, roundPricePerShare[withdrawalRound], vaultParams.decimals ); emit Withdraw(msg.sender, withdrawAmount, withdrawalShares); _burn(address(this), withdrawalShares); require(withdrawAmount > 0, "!withdrawAmount"); transferAsset(msg.sender, withdrawAmount); } /** * @notice Redeems shares that are owed to the account * @param numShares is the number of shares to redeem */ function redeem(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); _redeem(numShares, false); } /** * @notice Redeems the entire unredeemedShares balance that is owed to the account */ function maxRedeem() external nonReentrant { _redeem(0, true); } /** * @notice Redeems shares that are owed to the account * @param numShares is the number of shares to redeem, could be 0 when isMax=true * @param isMax is flag for when callers do a max redemption */ function _redeem(uint256 numShares, bool isMax) internal { Vault.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; // This handles the null case when depositReceipt.round = 0 // Because we start with round = 1 at `initialize` uint256 currentRound = vaultState.round; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); numShares = isMax ? unredeemedShares : numShares; if (numShares == 0) { return; } require(numShares <= unredeemedShares, "Exceeds available"); // If we have a depositReceipt on the same round, BUT we have some unredeemed shares // we debit from the unredeemedShares, but leave the amount field intact // If the round has past, with no new deposits, we just zero it out for new deposits. depositReceipts[msg.sender].amount = depositReceipt.round < currentRound ? 0 : depositReceipt.amount; ShareMath.assertUint128(numShares); depositReceipts[msg.sender].unredeemedShares = uint128( unredeemedShares.sub(numShares) ); emit Redeem(msg.sender, numShares, depositReceipt.round); _transfer(address(this), msg.sender, numShares); } /************************************************ * VAULT OPERATIONS ***********************************************/ /* * @notice Helper function that helps to save gas for writing values into the roundPricePerShare map. * Writing `1` into the map makes subsequent writes warm, reducing the gas from 20k to 5k. * Having 1 initialized beforehand will not be an issue as long as we round down share calculations to 0. * @param numRounds is the number of rounds to initialize in the map */ function initRounds(uint256 numRounds) external nonReentrant { require(numRounds > 0, "!numRounds"); uint256 _round = vaultState.round; for (uint256 i = 0; i < numRounds; i++) { uint256 index = _round + i; require(index >= _round, "Overflow"); require(roundPricePerShare[index] == 0, "Initialized"); // AVOID OVERWRITING ACTUAL VALUES roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT; } } /* * @notice Helper function that performs most administrative tasks * such as setting next option, minting new shares, getting vault fees, etc. * @return newOption is the new option address * @return lockedBalance is the new balance used to calculate next option purchase size or collateral size */ function _rollToNextOption() internal returns (address newOption, uint256 lockedBalance) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); ( uint256 _lockedBalance, uint256 queuedWithdrawAmount, uint256 newPricePerShare, uint256 mintShares ) = VaultLifecycle.rollover( totalSupply(), vaultParams.asset, vaultParams.decimals, uint256(vaultState.totalPending), vaultState.queuedWithdrawShares ); optionState.currentOption = newOption; optionState.nextOption = address(0); // Finalize the pricePerShare at the end of the round uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; // Take management / performance fee from previous round and deduct lockedBalance = _lockedBalance.sub( _collectVaultFees(_lockedBalance.add(queuedWithdrawAmount)) ); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); _mint(address(this), mintShares); return (newOption, lockedBalance); } /* * @notice Helper function that transfers management fees and performance fees from previous round. * @param pastWeekBalance is the balance we are about to lock for next round * @return vaultFee is the fee deducted */ function _collectVaultFees(uint256 pastWeekBalance) internal returns (uint256) { (uint256 performanceFeeInAsset, , uint256 vaultFee) = VaultLifecycle.getVaultFees( vaultState, pastWeekBalance, performanceFee, managementFee ); if (vaultFee > 0) { transferAsset(payable(feeRecipient), vaultFee); emit CollectVaultFees( performanceFeeInAsset, vaultFee, vaultState.round, feeRecipient ); } return vaultFee; } /** * @notice Helper function to make either an ETH transfer or ERC20 transfer * @param recipient is the receiving address * @param amount is the transfer amount */ function transferAsset(address recipient, uint256 amount) internal { address asset = vaultParams.asset; if (asset == WETH) { IWETH(WETH).withdraw(amount); (bool success, ) = recipient.call{value: amount}(""); require(success, "Transfer failed"); return; } IERC20(asset).safeTransfer(recipient, amount); } /************************************************ * GETTERS ***********************************************/ /** * @notice Returns the asset balance held on the vault for the account * @param account is the address to lookup balance for * @return the amount of `asset` custodied by the vault for the user */ function accountVaultBalance(address account) external view returns (uint256) { uint256 _decimals = vaultParams.decimals; uint256 assetPerShare = ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, _decimals ); return ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals); } /** * @notice Getter for returning the account's share balance including unredeemed shares * @param account is the account to lookup share balance for * @return the share balance */ function shares(address account) public view returns (uint256) { (uint256 heldByAccount, uint256 heldByVault) = shareBalances(account); return heldByAccount.add(heldByVault); } /** * @notice Getter for returning the account's share balance split between account and vault holdings * @param account is the account to lookup share balance for * @return heldByAccount is the shares held by account * @return heldByVault is the shares held on the vault (unredeemedShares) */ function shareBalances(address account) public view returns (uint256 heldByAccount, uint256 heldByVault) { Vault.DepositReceipt memory depositReceipt = depositReceipts[account]; if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) { return (balanceOf(account), 0); } uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( vaultState.round, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); return (balanceOf(account), unredeemedShares); } /** * @notice The price of a unit of share denominated in the `asset` */ function pricePerShare() external view returns (uint256) { return ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, vaultParams.decimals ); } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return uint256(vaultState.lockedAmount).add( IERC20(vaultParams.asset).balanceOf(address(this)) ); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return vaultParams.decimals; } function cap() external view returns (uint256) { return vaultParams.cap; } function nextOptionReadyAt() external view returns (uint256) { return optionState.nextOptionReadyAt; } function currentOption() external view returns (address) { return optionState.currentOption; } function nextOption() external view returns (address) { return optionState.nextOption; } function totalPending() external view returns (uint256) { return vaultState.totalPending; } /************************************************ * HELPERS ***********************************************/ } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {Vault} from "../libraries/Vault.sol"; interface IRibbonThetaVault { function currentOption() external view returns (address); function nextOption() external view returns (address); function vaultParams() external view returns (Vault.VaultParams memory); function vaultState() external view returns (Vault.VaultState memory); function optionState() external view returns (Vault.OptionState memory); function optionAuctionID() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT /// 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/>. pragma solidity >0.4.13; library DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint256 x, uint256 y) internal pure returns (uint256 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(uint256 x, uint256 n) internal pure returns (uint256 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); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AuctionType { struct AuctionData { IERC20 auctioningToken; IERC20 biddingToken; uint256 orderCancellationEndDate; uint256 auctionEndDate; bytes32 initialAuctionOrder; uint256 minimumBiddingAmountPerOrder; uint256 interimSumBidAmount; bytes32 interimOrder; bytes32 clearingPriceOrder; uint96 volumeClearingPriceOrder; bool minFundingThresholdNotReached; bool isAtomicClosureAllowed; uint256 feeNumerator; uint256 minFundingThreshold; } } interface IGnosisAuction { function initiateAuction( address _auctioningToken, address _biddingToken, uint256 orderCancellationEndDate, uint256 auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 minimumBiddingAmountPerOrder, uint256 minFundingThreshold, bool isAtomicClosureAllowed, address accessManagerContract, bytes memory accessManagerContractData ) external returns (uint256); function auctionCounter() external view returns (uint256); function auctionData(uint256 auctionId) external view returns (AuctionType.AuctionData memory); function auctionAccessManager(uint256 auctionId) external view returns (address); function auctionAccessData(uint256 auctionId) external view returns (bytes memory); function FEE_DENOMINATOR() external view returns (uint256); function feeNumerator() external view returns (uint256); function settleAuction(uint256 auctionId) external returns (bytes32); function placeSellOrders( uint256 auctionId, uint96[] memory _minBuyAmounts, uint96[] memory _sellAmounts, bytes32[] memory _prevSellOrders, bytes calldata allowListCallData ) external returns (uint64); function claimFromParticipantOrder( uint256 auctionId, bytes32[] memory orders ) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library GammaTypes { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral // in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } interface IOtoken { function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); } interface IOtokenFactory { function getOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); function createOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external returns (address); function getTargetOtokenAddress( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); event OtokenCreated( address tokenAddress, address creator, address indexed underlying, address indexed strike, address indexed collateral, uint256 strikePrice, uint256 expiry, bool isPut ); } interface IController { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets // but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function operate(ActionArgs[] calldata _actions) external; function getAccountVaultCounter(address owner) external view returns (uint256); function oracle() external view returns (address); function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory); function getProceed(address _owner, uint256 _vaultId) external view returns (uint256); function isSettlementAllowed( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IStrikeSelection { function getStrikePrice(uint256 expiryTimestamp, bool isPut) external view returns (uint256, uint256); function delta() external view returns (uint256); } interface IOptionsPremiumPricer { function getPremium( uint256 strikePrice, uint256 timeToExpiry, bool isPut ) external view returns (uint256); function getOptionDelta( uint256 spotPrice, uint256 strikePrice, uint256 volatility, uint256 expiryTimestamp ) external view returns (uint256 delta); function getUnderlyingPrice() external view returns (uint256); function priceOracle() external view returns (address); function volatilityOracle() external view returns (address); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Detailed is IERC20 { function decimals() external view returns (uint8); function symbol() external view returns (string calldata); function name() external view returns (string calldata); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * This library supports ERC20s that have quirks in their behavior. * One such ERC20 is USDT, which requires allowance to be 0 before calling approve. * We plan to update this library with ERC20s that display such idiosyncratic behavior. */ library SupportsNonCompliantERC20 { address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; function safeApproveNonCompliant( IERC20 token, address spender, uint256 amount ) internal { if (address(token) == USDT) { SafeERC20.safeApprove(token, spender, 0); } SafeERC20.safeApprove(token, spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); 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 {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
Creates the actual Opyn short position by depositing collateral and minting otokens gammaController is the address of the opyn controller contract marginPool is the address of the opyn margin contract which holds the collateral oTokenAddress is the address of the otoken to mint depositAmount is the amount of collateral to deposit return the otoken mint amount/ An otoken's collateralAsset is the vault's `asset` So in the context of performing Opyn short operations we call them collateralAsset For minting puts, there will be instances where the full depositAmount will not be used for minting. This is because of an issue with precision. For ETH put options, we are calculating the mintAmount (108 decimals) using the depositAmount (1018 decimals), which will result in truncation of decimals when scaling down. As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens. For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens. We retain the dust in the vault so the calling contract can withdraw the actual locked amount + dust at settlement. To test this behavior, we can console.log MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault) to see how much dust (or excess collateral) is left behind.
function createShort( address gammaController, address marginPool, address oTokenAddress, uint256 depositAmount ) external returns (uint256) { IController controller = IController(gammaController); uint256 newVaultID = (controller.getAccountVaultCounter(address(this))).add(1); IOtoken oToken = IOtoken(oTokenAddress); address collateralAsset = oToken.collateralAsset(); uint256 collateralDecimals = uint256(IERC20Detailed(collateralAsset).decimals()); uint256 mintAmount; if (oToken.isPut()) { mintAmount = depositAmount .mul(10**Vault.OTOKEN_DECIMALS) .div(oToken.strikePrice().mul(10**(10 + collateralDecimals))); mintAmount = depositAmount; if (mintAmount > scaleBy && collateralDecimals > 8) { } } collateralToken.safeApproveNonCompliant(marginPool, depositAmount); IController.ActionArgs[] memory actions = new IController.ActionArgs[](3); actions[0] = IController.ActionArgs( IController.ActionType.OpenVault, ); actions[1] = IController.ActionArgs( IController.ActionType.DepositCollateral, ); actions[2] = IController.ActionArgs( IController.ActionType.MintShortOption, ); controller.operate(actions); return mintAmount; }
1,176,241
./partial_match/1/0xEa5eDEF1169713C425ce57Cf5c154D732b1B7af6/sources/contracts/core/RcaShieldBase.sol
Update the amtForSale if there's an active fee./ If liquidation for claims is set incorrectly this could occur and break the contract.
function _update() internal { if (apr > 0) { uint256 balance = _uBalance(); if (balance < amtForSale) return; uint256 secsElapsed = block.timestamp - lastUpdate; uint256 active = balance - amtForSale; uint256 activeExclReserved = active - ((active * percentReserved) / DENOMINATOR); amtForSale += (activeExclReserved * secsElapsed * apr) / YEAR_SECS / DENOMINATOR; } lastUpdate = block.timestamp; }
2,777,719
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './FullMath.sol'; import './UnsafeMath.sol'; import './FixedPoint96.sol'; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { 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 toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol'; import '@uniswap/v3-periphery/contracts/libraries/PositionKey.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './interfaces/IHotPotV3FundDeployer.sol'; import './interfaces/IHotPotV3Fund.sol'; import './interfaces/external/IWETH9.sol'; import './base/HotPotV3FundERC20.sol'; import './libraries/Position.sol'; import './libraries/Array2D.sol'; contract HotPotV3Fund is HotPotV3FundERC20, IHotPotV3Fund, IUniswapV3MintCallback, ReentrancyGuard { using LowGasSafeMath for uint; using SafeCast for int256; using Path for bytes; using Position for Position.Info; using Position for Position.Info[]; using Array2D for uint[][]; uint public override depositDeadline = 2**256-1; uint public override immutable lockPeriod; uint public override immutable baseLine; uint public override immutable managerFee; uint constant FEE = 5; address immutable WETH9; address immutable uniV3Factory; address immutable uniV3Router; address public override immutable controller; address public override immutable manager; address public override immutable token; bytes public override descriptor; uint public override totalInvestment; /// @inheritdoc IHotPotV3FundState mapping (address => uint) override public investmentOf; /// @inheritdoc IHotPotV3FundState mapping(address => bytes) public override buyPath; /// @inheritdoc IHotPotV3FundState mapping(address => bytes) public override sellPath; /// @inheritdoc IHotPotV3FundState mapping(address => uint) public override lastDepositTime; /// @inheritdoc IHotPotV3FundState address[] public override pools; /// @inheritdoc IHotPotV3FundState Position.Info[][] public override positions; modifier onlyController() { require(msg.sender == controller, "OCC"); _; } modifier checkDeadline(uint deadline) { require(block.timestamp <= deadline, 'CDL'); _; } constructor () { address _token; address _uniV3Router; (WETH9, uniV3Factory, _uniV3Router, controller, manager, _token, descriptor, lockPeriod, baseLine, managerFee) = IHotPotV3FundDeployer(msg.sender).parameters(); token = _token; uniV3Router = _uniV3Router; //approve for add liquidity and swap. 2**256-1 never used up. TransferHelper.safeApprove(_token, _uniV3Router, 2**256-1); } /// @inheritdoc IHotPotV3FundUserActions function deposit(uint amount) external override returns(uint share) { require(amount > 0, "DAZ"); uint total_assets = totalAssets(); TransferHelper.safeTransferFrom(token, msg.sender, address(this), amount); return _deposit(amount, total_assets); } function _deposit(uint amount, uint total_assets) internal returns(uint share) { require(block.timestamp <= depositDeadline, "DL"); if(totalSupply == 0) share = amount; else share = FullMath.mulDiv(amount, totalSupply, total_assets); lastDepositTime[msg.sender] = block.timestamp; investmentOf[msg.sender] = investmentOf[msg.sender].add(amount); totalInvestment = totalInvestment.add(amount); _mint(msg.sender, share); emit Deposit(msg.sender, amount, share); } receive() external payable { //当前是WETH9基金 if(token == WETH9){ // 普通用户发起的转账ETH,认为是deposit if(msg.sender != WETH9 && msg.value > 0){ uint totals = totalAssets(); IWETH9(WETH9).deposit{value: address(this).balance}(); _deposit(msg.value, totals); } //else 接收WETH9向合约转账ETH } // 不是WETH基金, 不接受ETH转账 else revert(); } /// @inheritdoc IHotPotV3FundUserActions function withdraw(uint share, uint amountMin, uint deadline) external override checkDeadline(deadline) nonReentrant returns(uint amount) { uint balance = balanceOf[msg.sender]; require(share > 0 && share <= balance, "ISA"); require(block.timestamp > lastDepositTime[msg.sender].add(lockPeriod), "LKP"); uint investment = FullMath.mulDiv(investmentOf[msg.sender], share, balance); address fToken = token; // 构造amounts数组 uint value = IERC20(fToken).balanceOf(address(this)); uint _totalAssets = value; uint[][] memory amounts = new uint[][](pools.length); for(uint i=0; i<pools.length; i++){ uint _amount; (_amount, amounts[i]) = _assetsOfPool(i); _totalAssets = _totalAssets.add(_amount); } amount = FullMath.mulDiv(_totalAssets, share, totalSupply); // 从大到小从头寸中撤资. if(amount > value) { uint remainingAmount = amount.sub(value); while(true) { // 取最大的头寸索引号 (uint poolIndex, uint positionIndex, uint desirableAmount) = amounts.max(); if(desirableAmount == 0) break; if(remainingAmount <= desirableAmount){ positions[poolIndex][positionIndex].subLiquidity(Position.SubParams({ proportionX128: FullMath.mulDiv(remainingAmount, 100 << 128, desirableAmount), pool: pools[poolIndex], token: fToken, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory, maxSqrtSlippage: 10001, maxPriceImpact: 10001 }), sellPath); break; } else { positions[poolIndex][positionIndex].subLiquidity(Position.SubParams({ proportionX128: 100 << 128, pool: pools[poolIndex], token: fToken, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory, maxSqrtSlippage: 10001, maxPriceImpact: 10001 }), sellPath); remainingAmount = remainingAmount.sub(desirableAmount); amounts[poolIndex][positionIndex] = 0; } } /// @dev 从流动池中撤资时,按比例撤流动性, 同时tokensOwed已全部提取,所以此时的基金本币余额会超过用户可提金额. value = IERC20(fToken).balanceOf(address(this)); // 如果计算值比实际取出值大 if(amount > value) amount = value; // 如果是最后一个人withdraw else if(totalSupply == share) amount = value; } require(amount >= amountMin, 'PSC'); uint baseAmount = investment.add(investment.mul(baseLine) / 100); // 处理基金经理分成和基金分成 if(amount > baseAmount) { uint _manager_fee = (amount.sub(baseAmount)).mul(managerFee) / 100; uint _fee = (amount.sub(baseAmount)).mul(FEE) / 100; TransferHelper.safeTransfer(fToken, manager, _manager_fee); TransferHelper.safeTransfer(fToken, controller, _fee); amount = amount.sub(_fee).sub(_manager_fee); } else if(amount < investment)// 保留亏损的本金 investment = amount; // 处理转账 investmentOf[msg.sender] = investmentOf[msg.sender].sub(investment); totalInvestment = totalInvestment.sub(investment); _burn(msg.sender, share); if(fToken == WETH9){ IWETH9(WETH9).withdraw(amount); TransferHelper.safeTransferETH(msg.sender, amount); } else { TransferHelper.safeTransfer(fToken, msg.sender, amount); } emit Withdraw(msg.sender, amount, share); } /// @inheritdoc IHotPotV3FundState function poolsLength() external override view returns(uint){ return pools.length; } /// @inheritdoc IHotPotV3FundState function positionsLength(uint poolIndex) external override view returns(uint){ return positions[poolIndex].length; } /// @inheritdoc IHotPotV3FundManagerActions function setDescriptor(bytes calldata _descriptor) external override onlyController{ require(_descriptor.length > 0, "DES"); descriptor = _descriptor; emit SetDescriptor(_descriptor); } /// @inheritdoc IHotPotV3FundManagerActions function setDepositDeadline(uint deadline) external override onlyController{ require(block.timestamp < deadline, "DL"); depositDeadline = deadline; emit SetDeadline(deadline); } /// @inheritdoc IHotPotV3FundManagerActions function setPath( address distToken, bytes calldata buy, bytes calldata sell ) external override onlyController{ // 要修改sellPath, 需要先清空相关pool头寸资产 if(sellPath[distToken].length > 0){ for(uint i = 0; i < pools.length; i++){ IUniswapV3Pool pool = IUniswapV3Pool(pools[i]); if(pool.token0() == distToken || pool.token1() == distToken){ (uint amount,) = _assetsOfPool(i); require(amount == 0, "AZ"); } } } TransferHelper.safeApprove(distToken, uniV3Router, 0); TransferHelper.safeApprove(distToken, uniV3Router, 2**256-1); buyPath[distToken] = buy; sellPath[distToken] = sell; emit SetPath(distToken, buy); } /// @inheritdoc IUniswapV3MintCallback function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { address pool = pools[abi.decode(data, (uint))]; require(msg.sender == pool, "MQE"); // 转账给pool if (amount0Owed > 0) TransferHelper.safeTransfer(IUniswapV3Pool(pool).token0(), msg.sender, amount0Owed); if (amount1Owed > 0) TransferHelper.safeTransfer(IUniswapV3Pool(pool).token1(), msg.sender, amount1Owed); } /// @inheritdoc IHotPotV3FundManagerActions function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint32 maxPIS ) external override onlyController returns(uint128 liquidity){ // 1、检查pool是否有效 require(tickLower < tickUpper, "ITV"); require(token0 < token1, "ITV"); address pool = IUniswapV3Factory(uniV3Factory).getPool(token0, token1, fee); require(pool != address(0), "ITF"); int24 tickspacing = IUniswapV3Pool(pool).tickSpacing(); require(tickLower % tickspacing == 0, "TLV"); require(tickUpper % tickspacing == 0, "TUV"); // 2、添加流动池 bool hasPool = false; uint poolIndex; for(uint i = 0; i < pools.length; i++){ // 存在相同的流动池 if(pools[i] == pool) { hasPool = true; poolIndex = i; for(uint positionIndex = 0; positionIndex < positions[i].length; positionIndex++) { // 存在相同的头寸, 退出 if(positions[i][positionIndex].tickLower == tickLower) if(positions[i][positionIndex].tickUpper == tickUpper) revert(); } break; } } if(!hasPool) { pools.push(pool); positions.push(); poolIndex = pools.length - 1; } //3、新增头寸 positions[poolIndex].push(Position.Info({ isEmpty: true, tickLower: tickLower, tickUpper: tickUpper })); //4、投资 if(amount > 0){ address fToken = token; require(IERC20(fToken).balanceOf(address(this)) >= amount, "ATL"); Position.Info storage position = positions[poolIndex][positions[poolIndex].length - 1]; liquidity = position.addLiquidity(Position.AddParams({ poolIndex: poolIndex, pool: pool, amount: amount, amount0Max: 0, amount1Max: 0, token: fToken, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory, maxSqrtSlippage: maxPIS & 0xffff, maxPriceImpact: maxPIS >> 16 }), sellPath, buyPath); } emit Init(poolIndex, positions[poolIndex].length - 1, amount); } /// @inheritdoc IHotPotV3FundManagerActions function add( uint poolIndex, uint positionIndex, uint amount, bool collect, uint32 maxPIS ) external override onlyController returns(uint128 liquidity){ require(IERC20(token).balanceOf(address(this)) >= amount, "ATL"); require(poolIndex < pools.length, "IPL"); require(positionIndex < positions[poolIndex].length, "IPS"); uint amount0Max; uint amount1Max; Position.Info storage position = positions[poolIndex][positionIndex]; address pool = pools[poolIndex]; // 需要复投? if(collect) (amount0Max, amount1Max) = position.burnAndCollect(pool, 0); liquidity = position.addLiquidity(Position.AddParams({ poolIndex: poolIndex, pool: pool, amount: amount, amount0Max: amount0Max, amount1Max: amount1Max, token: token, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory, maxSqrtSlippage: maxPIS & 0xffff, maxPriceImpact: maxPIS >> 16 }), sellPath, buyPath); emit Add(poolIndex, positionIndex, amount, collect); } /// @inheritdoc IHotPotV3FundManagerActions function sub( uint poolIndex, uint positionIndex, uint proportionX128, uint32 maxPIS ) external override onlyController returns(uint amount){ require(poolIndex < pools.length, "IPL"); require(positionIndex < positions[poolIndex].length, "IPS"); amount = positions[poolIndex][positionIndex].subLiquidity(Position.SubParams({ proportionX128: proportionX128, pool: pools[poolIndex], token: token, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory, maxSqrtSlippage: maxPIS & 0xffff, maxPriceImpact: maxPIS >> 16 }), sellPath); emit Sub(poolIndex, positionIndex, proportionX128); } /// @inheritdoc IHotPotV3FundManagerActions function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, uint32 maxPIS ) external override onlyController returns(uint128 liquidity){ require(poolIndex < pools.length, "IPL"); require(subIndex < positions[poolIndex].length, "ISI"); require(addIndex < positions[poolIndex].length, "IAI"); // 移除 (uint amount0Max, uint amount1Max) = positions[poolIndex][subIndex] .burnAndCollect(pools[poolIndex], proportionX128); // 添加 liquidity = positions[poolIndex][addIndex].addLiquidity(Position.AddParams({ poolIndex: poolIndex, pool: pools[poolIndex], amount: 0, amount0Max: amount0Max, amount1Max: amount1Max, token: token, uniV3Router: uniV3Router, uniV3Factory: uniV3Factory, maxSqrtSlippage: maxPIS & 0xffff, maxPriceImpact: maxPIS >> 16 }), sellPath, buyPath); emit Move(poolIndex, subIndex, addIndex, proportionX128); } /// @inheritdoc IHotPotV3FundState function assetsOfPosition(uint poolIndex, uint positionIndex) public override view returns (uint amount) { return positions[poolIndex][positionIndex].assets(pools[poolIndex], token, sellPath, uniV3Factory); } /// @inheritdoc IHotPotV3FundState function assetsOfPool(uint poolIndex) public view override returns (uint amount) { (amount, ) = _assetsOfPool(poolIndex); } /// @inheritdoc IHotPotV3FundState function totalAssets() public view override returns (uint amount) { amount = IERC20(token).balanceOf(address(this)); for(uint i = 0; i < pools.length; i++){ uint _amount; (_amount, ) = _assetsOfPool(i); amount = amount.add(_amount); } } function _assetsOfPool(uint poolIndex) internal view returns (uint amount, uint[] memory) { return positions[poolIndex].assetsOfPool(pools[poolIndex], token, sellPath, uniV3Factory); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; import "@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol"; import "../interfaces/IHotPotV3FundERC20.sol"; abstract contract HotPotV3FundERC20 is IHotPotV3FundERC20{ using LowGasSafeMath for uint; string public override constant name = 'Hotpot V3'; string public override constant symbol = 'HPT-V3'; uint8 public override constant decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; constructor() { } function _mint(address to, uint value) internal { require(to != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { require(from != address(0), "ERC20: burn from the zero address"); balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowance[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function _transfer(address from, address to, uint value) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint value ) external override returns (bool) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); _transfer(from, to, value); return true; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './IHotPotV3FundERC20.sol'; import './fund/IHotPotV3FundEvents.sol'; import './fund/IHotPotV3FundState.sol'; import './fund/IHotPotV3FundUserActions.sol'; import './fund/IHotPotV3FundManagerActions.sol'; /// @title Hotpot V3 基金接口 /// @notice 接口定义分散在多个接口文件 interface IHotPotV3Fund is IHotPotV3FundERC20, IHotPotV3FundEvents, IHotPotV3FundState, IHotPotV3FundUserActions, IHotPotV3FundManagerActions { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title An interface for a contract that is capable of deploying Hotpot V3 Funds /// @notice A contract that constructs a fund must implement this to pass arguments to the fund /// @dev This is used to avoid having constructor arguments in the fund contract, which results in the init code hash /// of the fund being constant allowing the CREATE2 address of the fund to be cheaply computed on-chain interface IHotPotV3FundDeployer { /// @notice Get the parameters to be used in constructing the fund, set transiently during fund creation. /// @dev Called by the fund constructor to fetch the parameters of the fund /// Returns controller The controller address /// Returns manager The manager address of this fund /// Returns token The local token address /// Returns descriptor bytes string descriptor, the first 32 bytes manager name + next bytes brief description /// Returns lockPeriod Fund lock up period /// Returns baseLine Baseline of fund manager fee ratio /// Returns managerFee When the ROI is greater than the baseline, the fund manager’s fee ratio function parameters() external view returns ( address weth9, address uniV3Factory, address uniswapV3Router, address controller, address manager, address token, bytes memory descriptor, uint lockPeriod, uint baseLine, uint managerFee ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Hotpot V3 基金份额代币接口定义 interface IHotPotV3FundERC20 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: GPL-2.0-or-later pragma solidity =0.7.6; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 事件接口定义 interface IHotPotV3FundEvents { /// @notice 当存入基金token时,会触发该事件 event Deposit(address indexed owner, uint amount, uint share); /// @notice 当取走基金token时,会触发该事件 event Withdraw(address indexed owner, uint amount, uint share); /// @notice 当调用setDescriptor时触发 event SetDescriptor(bytes descriptor); /// @notice 当调用setDepositDeadline时触发 event SetDeadline(uint deadline); /// @notice 当调用setPath时触发 event SetPath(address distToken, bytes path); /// @notice 当调用init时,会触发该事件 event Init(uint poolIndex, uint positionIndex, uint amount); /// @notice 当调用add时,会触发该事件 event Add(uint poolIndex, uint positionIndex, uint amount, bool collect); /// @notice 当调用sub时,会触发该事件 event Sub(uint poolIndex, uint positionIndex, uint proportionX128); /// @notice 当调用move时,会触发该事件 event Move(uint poolIndex, uint subIndex, uint addIndex, uint proportionX128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @notice 基金经理操作接口定义 interface IHotPotV3FundManagerActions { /// @notice 设置基金描述信息 /// @dev This function can only be called by controller /// @param _descriptor 描述信息 function setDescriptor(bytes calldata _descriptor) external; /// @notice 设置基金存入截止时间 /// @dev This function can only be called by controller /// @param deadline 最晚存入截止时间 function setDepositDeadline(uint deadline) external; /// @notice 设置代币交易路径 /// @dev This function can only be called by controller /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param distToken 目标代币地址 /// @param buy 购买路径(本币->distToken) /// @param sell 销售路径(distToken->本币) function setPath( address distToken, bytes calldata buy, bytes calldata sell ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by controller /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 添加的lp数量 function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint32 maxPIS ) external returns(uint128 liquidity); /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 添加的lp数量 function add( uint poolIndex, uint positionIndex, uint amount, bool collect, uint32 maxPIS ) external returns(uint128 liquidity); /// @notice 撤资指定头寸 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 /// @param maxPIS 最大价格影响和价格滑点 /// @return amount 撤资获得的基金本币数量 function sub( uint poolIndex, uint positionIndex, uint proportionX128, uint32 maxPIS ) external returns(uint amount); /// @notice 调整头寸投资 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 调整后添加的lp数量 function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了 uint32 maxPIS ) external returns(uint128 liquidity); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 状态变量及只读函数 interface IHotPotV3FundState { /// @notice 控制器合约地址 function controller() external view returns (address); /// @notice 基金经理地址 function manager() external view returns (address); /// @notice 基金本币地址 function token() external view returns (address); /// @notice 32 bytes 基金经理 + 任意长度的简要描述 function descriptor() external view returns (bytes memory); /// @notice 基金锁定期 function lockPeriod() external view returns (uint); /// @notice 基金经理收费基线 function baseLine() external view returns (uint); /// @notice 基金经理收费比例 function managerFee() external view returns (uint); /// @notice 基金存入截止时间 function depositDeadline() external view returns (uint); /// @notice 获取最新存入时间 /// @param account 目标地址 /// @return 最新存入时间 function lastDepositTime(address account) external view returns (uint); /// @notice 总投入数量 function totalInvestment() external view returns (uint); /// @notice owner的投入数量 /// @param owner 用户地址 /// @return 投入本币的数量 function investmentOf(address owner) external view returns (uint); /// @notice 指定头寸的资产数量 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return 以本币计价的头寸资产数量 function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint); /// @notice 指定pool的资产数量 /// @param poolIndex 池子索引号 /// @return 以本币计价的池子资产数量 function assetsOfPool(uint poolIndex) external view returns(uint); /// @notice 总资产数量 /// @return 以本币计价的总资产数量 function totalAssets() external view returns (uint); /// @notice 基金本币->目标代币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币购买路径 function buyPath(address _token) external view returns (bytes memory); /// @notice 目标代币->基金本币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币销售路径 function sellPath(address _token) external view returns (bytes memory); /// @notice 获取池子地址 /// @param index 池子索引号 /// @return 池子地址 function pools(uint index) external view returns(address); /// @notice 头寸信息 /// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届 function positions(uint poolIndex, uint positionIndex) external view returns( bool isEmpty, int24 tickLower, int24 tickUpper ); /// @notice pool数组长度 function poolsLength() external view returns(uint); /// @notice 指定池子的头寸数组长度 /// @param poolIndex 池子索引号 /// @return 头寸数组长度 function positionsLength(uint poolIndex) external view returns(uint); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 用户操作接口定义 /// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账; interface IHotPotV3FundUserActions { /// @notice 用户存入基金本币 /// @param amount 存入数量 /// @return share 用户获得的基金份额 function deposit(uint amount) external returns(uint share); /// @notice 用户取出指定份额的本币 /// @param share 取出的基金份额数量 /// @param amountMin 最小提取值 /// @param deadline 最晚交易时间 /// @return amount 返回本币数量 function withdraw(uint share, uint amountMin, uint deadline) external returns(uint amount); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.5; pragma abicoder v2; library Array2D { /// @notice 取二维数组中最大值及索引 /// @param self 二维数组 /// @return index1 一维索引 /// @return index2 二维索引 /// @return value 最大值 function max(uint[][] memory self) internal pure returns( uint index1, uint index2, uint value ) { for(uint i = 0; i < self.length; i++){ for(uint j = 0; j < self[i].length; j++){ if(self[i][j] > value){ (index1, index2, value) = (i, j, self[i][j]); } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint64 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint64 { uint256 internal constant Q64 = 0x10000000000000000; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol"; import "./FixedPoint64.sol"; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol"; import "@uniswap/v3-periphery/contracts/libraries/Path.sol"; library PathPrice { using Path for bytes; /// @notice 获取目标代币当前价格的平方根 /// @param path 兑换路径 /// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96( bytes memory path, address uniV3Factory ) internal view returns (uint sqrtPriceX96){ require(path.length > 0, "IPL"); sqrtPriceX96 = FixedPoint96.Q96; uint _nextSqrtPriceX96; uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); (_nextSqrtPriceX96,,,,,,) = pool.slot0(); sqrtPriceX96 = tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _nextSqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96, _nextSqrtPriceX96, FixedPoint96.Q96); // decide whether to continue or terminate if (path.hasMultiplePools()) path = path.skipToken(); else break; } } /// @notice 获取目标代币预言机价格的平方根 /// @param path 兑换路径 /// @return sqrtPriceX96Last 预言机价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96Last( bytes memory path, address uniV3Factory ) internal view returns (uint sqrtPriceX96Last){ require(path.length > 0, "IPL"); sqrtPriceX96Last = FixedPoint96.Q96; uint _nextSqrtPriceX96; uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); // sqrtPriceX96Last (int56[] memory tickCumulatives,) = pool.observe(secondAges); _nextSqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1])); sqrtPriceX96Last = tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96Last, FixedPoint96.Q96, _nextSqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96Last, _nextSqrtPriceX96, FixedPoint96.Q96); // decide whether to continue or terminate if (path.hasMultiplePools()) path = path.skipToken(); else break; } } /// @notice 验证交易滑点是否满足条件 /// @param path 兑换路径 /// @param uniV3Factory uniswap v3 factory /// @param maxSqrtSlippage 最大滑点,最大值: 1e4 /// @return 当前价 function verifySlippage( bytes memory path, address uniV3Factory, uint32 maxSqrtSlippage ) internal view returns(uint) { uint last = getSqrtPriceX96Last(path, uniV3Factory); uint current = getSqrtPriceX96(path, uniV3Factory); if(last > current) require(current > FullMath.mulDiv(maxSqrtSlippage, last, 1e4), "VS"); return current; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.5; pragma abicoder v2; import './PathPrice.sol'; import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol"; import '@uniswap/v3-periphery/contracts/libraries/PositionKey.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import "@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol"; library Position { using LowGasSafeMath for uint; using SafeCast for int256; // using Path for bytes; uint constant DIVISOR = 100 << 128; // info stored for each user's position struct Info { bool isEmpty; int24 tickLower; int24 tickUpper; } /// @notice 计算将t0最大化添加到pool的LP时,需要的t0, t1数量 /// @dev 计算公式:△x0 = △x /( SPu*(SPc - SPl) / (SPc*(SPu - SPc)) + 1) function getAmountsForAmount0( uint160 sqrtPriceX96, uint160 sqrtPriceL96, uint160 sqrtPriceU96, uint deltaX ) internal pure returns(uint amount0, uint amount1){ // 全部是t0 if(sqrtPriceX96 <= sqrtPriceL96){ amount0 = deltaX; } // 部分t0 else if( sqrtPriceX96 < sqrtPriceU96){ // a = SPu*(SPc - SPl) uint a = FullMath.mulDiv(sqrtPriceU96, sqrtPriceX96 - sqrtPriceL96, FixedPoint64.Q64); // b = SPc*(SPu - SPc) uint b = FullMath.mulDiv(sqrtPriceX96, sqrtPriceU96 - sqrtPriceX96, FixedPoint64.Q64); // △x0 = △x/(a/b +1) = △x*b/(a+b) amount0 = FullMath.mulDiv(deltaX, b, a + b); } // 剩余的转成t1 if(deltaX > amount0){ amount1 = FullMath.mulDiv( deltaX.sub(amount0), FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint64.Q64), FixedPoint128.Q128 ); } } /// @notice 计算最小兑换输出值 /// @param curSqrtPirceX96 当前价 /// @param maxPriceImpact 最大价格影响 /// @param amountIn 输入数里 function getAmountOutMin( uint curSqrtPirceX96, uint maxPriceImpact, uint amountIn ) internal pure returns(uint amountOutMin){ amountOutMin = FullMath.mulDiv( FullMath.mulDiv(amountIn, FullMath.mulDiv(curSqrtPirceX96, curSqrtPirceX96, FixedPoint64.Q64), FixedPoint128.Q128), 1e4 - maxPriceImpact, // maxPriceImpact最大1e4,不会溢出 1e4); } struct SwapParams{ uint amount; uint amount0; uint amount1; uint160 sqrtPriceX96; uint160 sqrtRatioAX96; uint160 sqrtRatioBX96; address token; address token0; address token1; uint24 fee; address uniV3Factory; address uniV3Router; uint32 maxSqrtSlippage; uint32 maxPriceImpact; } /// @notice 根据基金本币数量以及收集的手续费数量, 计算投资指定头寸两种代币的分布. function computeSwapAmounts( SwapParams memory params, mapping(address => bytes) storage buyPath ) internal returns(uint amount0Max, uint amount1Max) { uint equalAmount0; bytes memory buy0Path; bytes memory buy1Path; uint buy0SqrtPriceX96; uint buy1SqrtPriceX96; uint amountIn; //将基金本币换算成token0 if(params.amount > 0){ if(params.token == params.token0){ buy1Path = buyPath[params.token1]; buy1SqrtPriceX96 = PathPrice.verifySlippage(buy1Path, params.uniV3Factory, params.maxSqrtSlippage); equalAmount0 = params.amount0.add(params.amount); } else { buy0Path = buyPath[params.token0]; buy0SqrtPriceX96 = PathPrice.verifySlippage(buy0Path, params.uniV3Factory, params.maxSqrtSlippage); if(params.token != params.token1) { buy1Path = buyPath[params.token1]; buy1SqrtPriceX96 = PathPrice.verifySlippage(buy1Path, params.uniV3Factory, params.maxSqrtSlippage); } equalAmount0 = params.amount0.add((FullMath.mulDiv( params.amount, FullMath.mulDiv(buy0SqrtPriceX96, buy0SqrtPriceX96, FixedPoint64.Q64), FixedPoint128.Q128 ))); } } else equalAmount0 = params.amount0; //将token1换算成token0 if(params.amount1 > 0){ equalAmount0 = equalAmount0.add((FullMath.mulDiv( params.amount1, FixedPoint128.Q128, FullMath.mulDiv(params.sqrtPriceX96, params.sqrtPriceX96, FixedPoint64.Q64) ))); } require(equalAmount0 > 0, "EIZ"); // 计算需要的t0、t1数量 (amount0Max, amount1Max) = getAmountsForAmount0(params.sqrtPriceX96, params.sqrtRatioAX96, params.sqrtRatioBX96, equalAmount0); // t0不够,需要补充 if(amount0Max > params.amount0) { //t1也不够,基金本币需要兑换成t0和t1 if(amount1Max > params.amount1){ // 基金本币兑换成token0 if(params.token0 == params.token){ amountIn = amount0Max - params.amount0; if(amountIn > params.amount) amountIn = params.amount; amount0Max = params.amount0.add(amountIn); } else { amountIn = FullMath.mulDiv( amount0Max - params.amount0, FixedPoint128.Q128, FullMath.mulDiv(buy0SqrtPriceX96, buy0SqrtPriceX96, FixedPoint64.Q64) ); if(amountIn > params.amount) amountIn = params.amount; if(amountIn > 0) { uint amountOutMin = getAmountOutMin(buy0SqrtPriceX96, params.maxPriceImpact, amountIn); amount0Max = params.amount0.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buy0Path, recipient: address(this), deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: amountOutMin }))); } else amount0Max = params.amount0; } // 基金本币兑换成token1 if(params.token1 == params.token){ amount1Max = params.amount1.add(params.amount.sub(amountIn)); } else { if(amountIn < params.amount){ amountIn = params.amount.sub(amountIn); uint amountOutMin = getAmountOutMin(buy1SqrtPriceX96, params.maxPriceImpact, amountIn); amount1Max = params.amount1.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buy1Path, recipient: address(this), deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: amountOutMin }))); } else amount1Max = params.amount1; } } // t1多了,多余的t1需要兑换成t0,基金本币全部兑换成t0 else { // 基金本币全部兑换成t0 if (params.amount > 0){ if(params.token0 == params.token){ amount0Max = params.amount0.add(params.amount); } else{ uint amountOutMin = getAmountOutMin(buy0SqrtPriceX96, params.maxPriceImpact, params.amount); amount0Max = params.amount0.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buy0Path, recipient: address(this), deadline: block.timestamp, amountIn: params.amount, amountOutMinimum: amountOutMin }))); } } else amount0Max = params.amount0; // 多余的t1兑换成t0 if(params.amount1 > amount1Max) { amountIn = params.amount1.sub(amount1Max); buy0Path = abi.encodePacked(params.token1, params.fee, params.token0); buy0SqrtPriceX96 = FixedPoint96.Q96 * FixedPoint96.Q96 / params.sqrtPriceX96;// 不会出现溢出 uint lastSqrtPriceX96 = PathPrice.getSqrtPriceX96Last(buy0Path, params.uniV3Factory); if(lastSqrtPriceX96 > buy0SqrtPriceX96) require(buy0SqrtPriceX96 > params.maxSqrtSlippage * lastSqrtPriceX96 / 1e4, "VS");// 不会出现溢出 uint amountOutMin = getAmountOutMin(buy0SqrtPriceX96, params.maxPriceImpact, amountIn); amount0Max = amount0Max.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buy0Path, recipient: address(this), deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: amountOutMin }))); } } } // t0多了,多余的t0兑换成t1, 基金本币全部兑换成t1 else { // 基金本币全部兑换成t1 if(params.amount > 0){ if(params.token1 == params.token){ amount1Max = params.amount1.add(params.amount); } else { uint amountOutMin = getAmountOutMin(buy1SqrtPriceX96, params.maxPriceImpact, params.amount); amount1Max = params.amount1.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buy1Path, recipient: address(this), deadline: block.timestamp, amountIn: params.amount, amountOutMinimum: amountOutMin }))); } } else amount1Max = params.amount1; // 多余的t0兑换成t1 if(params.amount0 > amount0Max){ amountIn = params.amount0.sub(amount0Max); buy1Path = abi.encodePacked(params.token0, params.fee, params.token1); buy1SqrtPriceX96 = params.sqrtPriceX96; uint lastSqrtPriceX96 = PathPrice.getSqrtPriceX96Last(buy1Path, params.uniV3Factory); if(lastSqrtPriceX96 > buy1SqrtPriceX96) require(buy1SqrtPriceX96 > params.maxSqrtSlippage * lastSqrtPriceX96 / 1e4, "VS");// 不会出现溢出 uint amountOutMin = getAmountOutMin(buy1SqrtPriceX96, params.maxPriceImpact, amountIn); amount1Max = amount1Max.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: buy1Path, recipient: address(this), deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: amountOutMin }))); } } } struct AddParams { // pool信息 uint poolIndex; address pool; // 要投入的基金本币和数量 address token; uint amount; // 要投入的token0、token1数量 uint amount0Max; uint amount1Max; //UNISWAP_V3_ROUTER address uniV3Router; address uniV3Factory; uint32 maxSqrtSlippage; uint32 maxPriceImpact; } /// @notice 添加LP到指定Position /// @param self Position.Info /// @param params 投资信息 /// @param sellPath sell token路径 /// @param buyPath buy token路径 function addLiquidity( Info storage self, AddParams memory params, mapping(address => bytes) storage sellPath, mapping(address => bytes) storage buyPath ) public returns(uint128 liquidity) { (int24 tickLower, int24 tickUpper) = (self.tickLower, self.tickUpper); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(params.pool).slot0(); SwapParams memory swapParams = SwapParams({ amount: params.amount, amount0: params.amount0Max, amount1: params.amount1Max, sqrtPriceX96: sqrtPriceX96, sqrtRatioAX96: TickMath.getSqrtRatioAtTick(tickLower), sqrtRatioBX96: TickMath.getSqrtRatioAtTick(tickUpper), token: params.token, token0: IUniswapV3Pool(params.pool).token0(), token1: IUniswapV3Pool(params.pool).token1(), fee: IUniswapV3Pool(params.pool).fee(), uniV3Router: params.uniV3Router, uniV3Factory: params.uniV3Factory, maxSqrtSlippage: params.maxSqrtSlippage, maxPriceImpact: params.maxPriceImpact }); (params.amount0Max, params.amount1Max) = computeSwapAmounts(swapParams, buyPath); //因为滑点,重新加载sqrtPriceX96 (sqrtPriceX96,,,,,,) = IUniswapV3Pool(params.pool).slot0(); //推算实际的liquidity liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, swapParams.sqrtRatioAX96, swapParams.sqrtRatioBX96, params.amount0Max, params.amount1Max); require(liquidity > 0, "LIZ"); (uint amount0, uint amount1) = IUniswapV3Pool(params.pool).mint( address(this),// LP recipient tickLower, tickUpper, liquidity, abi.encode(params.poolIndex) ); //处理没有添加进LP的token余额,兑换回基金本币 if(amount0 < params.amount0Max){ if(swapParams.token0 != params.token){ ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: sellPath[swapParams.token0], recipient: address(this), deadline: block.timestamp, amountIn: params.amount0Max - amount0, amountOutMinimum: 0 })); } } if(amount1 < params.amount1Max){ if(swapParams.token1 != params.token){ ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: sellPath[swapParams.token1], recipient: address(this), deadline: block.timestamp, amountIn: params.amount1Max - amount1, amountOutMinimum: 0 })); } } if(self.isEmpty) self.isEmpty = false; } /// @notice brun指定头寸的LP,并取回2种代币 /// @param pool UniswapV3Pool /// @param proportionX128 burn所占份额 /// @return amount0 获得的token0数量 /// @return amount1 获得的token1数量 function burnAndCollect( Info storage self, address pool, uint proportionX128 ) public returns(uint amount0, uint amount1) { require(proportionX128 <= DIVISOR, "PTL"); // 如果是空头寸,直接返回0,0 if(self.isEmpty == true) return(amount0, amount1); int24 tickLower = self.tickLower; int24 tickUpper = self.tickUpper; IUniswapV3Pool _pool = IUniswapV3Pool(pool); if(proportionX128 > 0) { (uint sumLP, , , , ) = _pool.positions(PositionKey.compute(address(this), tickLower, tickUpper)); uint subLP = FullMath.mulDiv(proportionX128, sumLP, DIVISOR); _pool.burn(tickLower, tickUpper, uint128(subLP)); (amount0, amount1) = _pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max); if(sumLP == subLP) self.isEmpty = true; } //为0表示只提取手续费 else { _pool.burn(tickLower, tickUpper, 0); (amount0, amount1) = _pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max); } } struct SubParams { //pool信息 address pool; //基金本币和移除占比 address token; uint proportionX128; //UNISWAP_V3_ROUTER address uniV3Router; address uniV3Factory; uint32 maxSqrtSlippage; uint32 maxPriceImpact; } /// @notice 减少指定头寸LP,并取回本金本币 /// @param self 指定头寸 /// @param params 流动池和要减去的数量 /// @return amount 获取的基金本币数量 function subLiquidity ( Info storage self, SubParams memory params, mapping(address => bytes) storage sellPath ) public returns(uint amount) { address token0 = IUniswapV3Pool(params.pool).token0(); address token1 = IUniswapV3Pool(params.pool).token1(); uint sqrtPriceX96; uint sqrtPriceX96Last; uint amountOutMin; // 验证本池子的滑点 if(params.maxSqrtSlippage <= 1e4){ // t0到t1的滑点 (sqrtPriceX96,,,,,,) = IUniswapV3Pool(params.pool).slot0(); uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; (int56[] memory tickCumulatives,) = IUniswapV3Pool(params.pool).observe(secondAges); sqrtPriceX96Last = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1])); if(sqrtPriceX96Last > sqrtPriceX96) require(sqrtPriceX96 > params.maxSqrtSlippage * sqrtPriceX96Last / 1e4, "VS");// 不会出现溢出 // t1到t0的滑点 sqrtPriceX96 = FixedPoint96.Q96 * FixedPoint96.Q96 / sqrtPriceX96; // 不会出现溢出 sqrtPriceX96Last = FixedPoint96.Q96 * FixedPoint96.Q96 / sqrtPriceX96Last; if(sqrtPriceX96Last > sqrtPriceX96) require(sqrtPriceX96 > params.maxSqrtSlippage * sqrtPriceX96Last / 1e4, "VS"); // 不会出现溢出 } // burn & collect (uint amount0, uint amount1) = burnAndCollect(self, params.pool, params.proportionX128); // t0兑换成基金本币 if(token0 != params.token){ if(amount0 > 0){ bytes memory path = sellPath[token0]; if(params.maxSqrtSlippage <= 1e4) { sqrtPriceX96 = PathPrice.verifySlippage(path, params.uniV3Factory, params.maxSqrtSlippage); amountOutMin = getAmountOutMin(sqrtPriceX96, params.maxPriceImpact, amount0); } amount = ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: path, recipient: address(this), deadline: block.timestamp, amountIn: amount0, amountOutMinimum: amountOutMin })); } } // t1兑换成基金本币 if(token1 != params.token){ if(amount1 > 0){ bytes memory path = sellPath[token1]; if(params.maxSqrtSlippage <= 1e4) { sqrtPriceX96 = PathPrice.verifySlippage(path, params.uniV3Factory, params.maxSqrtSlippage); amountOutMin = getAmountOutMin(sqrtPriceX96, params.maxPriceImpact, amount1); } amount = amount.add(ISwapRouter(params.uniV3Router).exactInput(ISwapRouter.ExactInputParams({ path: path, recipient: address(this), deadline: block.timestamp, amountIn: amount1, amountOutMinimum: amountOutMin }))); } } } /// @notice 封装成结构体的函数局部变量,避免堆栈过深报错. struct AssetsParams { address token0; address token1; uint sqrt0; uint sqrt1; uint160 sqrtPriceX96; int24 tick; uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; } /// @notice 获取某个流动池(pool),以基金本币衡量的所有资产 /// @param pool 流动池地址 /// @return amount 资产数量 function assetsOfPool( Info[] storage self, address pool, address token, mapping(address => bytes) storage sellPath, address uniV3Factory ) public view returns (uint amount, uint[] memory) { uint[] memory amounts = new uint[](self.length); // 局部变量都是为了减少ssload消耗. AssetsParams memory params; // 获取两种token的本币价格. params.token0 = IUniswapV3Pool(pool).token0(); params.token1 = IUniswapV3Pool(pool).token1(); if(params.token0 != token){ bytes memory path = sellPath[params.token0]; if(path.length == 0) return(amount, amounts); params.sqrt0 = PathPrice.getSqrtPriceX96Last(path, uniV3Factory); } if(params.token1 != token){ bytes memory path = sellPath[params.token1]; if(path.length == 0) return(amount, amounts); params.sqrt1 = PathPrice.getSqrtPriceX96Last(path, uniV3Factory); } (params.sqrtPriceX96, params.tick, , , , , ) = IUniswapV3Pool(pool).slot0(); params.feeGrowthGlobal0X128 = IUniswapV3Pool(pool).feeGrowthGlobal0X128(); params.feeGrowthGlobal1X128 = IUniswapV3Pool(pool).feeGrowthGlobal1X128(); for(uint i=0; i < self.length; i++){ Position.Info memory position = self[i]; if(position.isEmpty) continue; bytes32 positionKey = keccak256(abi.encodePacked(address(this), position.tickLower, position.tickUpper)); // 获取token0, token1的资产数量 (uint256 _amount0, uint256 _amount1) = getAssetsOfSinglePosition( AssetsOfSinglePosition({ pool: pool, positionKey: positionKey, tickLower: position.tickLower, tickUpper: position.tickUpper, tickCurrent: params.tick, sqrtPriceX96: params.sqrtPriceX96, feeGrowthGlobal0X128: params.feeGrowthGlobal0X128, feeGrowthGlobal1X128: params.feeGrowthGlobal1X128 }) ); // 计算成本币资产. uint _amount; if(params.token0 != token){ _amount = FullMath.mulDiv( _amount0, FullMath.mulDiv(params.sqrt0, params.sqrt0, FixedPoint64.Q64), FixedPoint128.Q128); } else _amount = _amount0; if(params.token1 != token){ _amount = _amount.add(FullMath.mulDiv( _amount1, FullMath.mulDiv(params.sqrt1, params.sqrt1, FixedPoint64.Q64), FixedPoint128.Q128)); } else _amount = _amount.add(_amount1); amounts[i] = _amount; amount = amount.add(_amount); } return(amount, amounts); } /// @notice 获取某个头寸,以基金本币衡量的所有资产 /// @param pool 交易池索引号 /// @param token 头寸索引号 /// @return amount 资产数量 function assets( Info storage self, address pool, address token, mapping(address => bytes) storage sellPath, address uniV3Factory ) public view returns (uint amount) { if(self.isEmpty) return 0; // 不需要校验 pool 是否存在 (uint160 sqrtPriceX96, int24 tick, , , , , ) = IUniswapV3Pool(pool).slot0(); bytes32 positionKey = keccak256(abi.encodePacked(address(this), self.tickLower, self.tickUpper)); // 获取token0, token1的资产数量 (uint256 amount0, uint256 amount1) = getAssetsOfSinglePosition( AssetsOfSinglePosition({ pool: pool, positionKey: positionKey, tickLower: self.tickLower, tickUpper: self.tickUpper, tickCurrent: tick, sqrtPriceX96: sqrtPriceX96, feeGrowthGlobal0X128: IUniswapV3Pool(pool).feeGrowthGlobal0X128(), feeGrowthGlobal1X128: IUniswapV3Pool(pool).feeGrowthGlobal1X128() }) ); // 计算以本币衡量的资产. if(amount0 > 0){ address token0 = IUniswapV3Pool(pool).token0(); if(token0 != token){ uint sqrt0 = PathPrice.getSqrtPriceX96Last(sellPath[token0], uniV3Factory); amount = FullMath.mulDiv( amount0, FullMath.mulDiv(sqrt0, sqrt0, FixedPoint64.Q64), FixedPoint128.Q128); } else amount = amount0; } if(amount1 > 0){ address token1 = IUniswapV3Pool(pool).token1(); if(token1 != token){ uint sqrt1 = PathPrice.getSqrtPriceX96Last(sellPath[token1], uniV3Factory); amount = amount.add(FullMath.mulDiv( amount1, FullMath.mulDiv(sqrt1, sqrt1, FixedPoint64.Q64), FixedPoint128.Q128)); } else amount = amount.add(amount1); } } /// @notice 封装成结构体的函数调用参数. struct AssetsOfSinglePosition { // 交易对地址. address pool; // 头寸ID bytes32 positionKey; // 价格刻度下届 int24 tickLower; // 价格刻度上届 int24 tickUpper; // 当前价格刻度 int24 tickCurrent; // 当前价格 uint160 sqrtPriceX96; // 全局手续费变量(token0) uint256 feeGrowthGlobal0X128; // 全局手续费变量(token1) uint256 feeGrowthGlobal1X128; } /// @notice 获取某个头寸的全部资产,包括未计算进tokensOwed的手续费. /// @param params 封装成结构体的函数调用参数. /// @return amount0 token0的数量 /// @return amount1 token1的数量 function getAssetsOfSinglePosition(AssetsOfSinglePosition memory params) internal view returns (uint256 amount0, uint256 amount1) { ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = IUniswapV3Pool(params.pool).positions(params.positionKey); // 计算未计入tokensOwed的手续费 (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside( FeeGrowthInsideParams({ pool: params.pool, tickLower: params.tickLower, tickUpper: params.tickUpper, tickCurrent: params.tickCurrent, feeGrowthGlobal0X128: params.feeGrowthGlobal0X128, feeGrowthGlobal1X128: params.feeGrowthGlobal1X128 }) ); // calculate accumulated fees amount0 = uint256( FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ) ); amount1 = uint256( FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ) ); // 计算总的手续费. // overflow is acceptable, have to withdraw before you hit type(uint128).max fees amount0 = amount0.add(tokensOwed0); amount1 = amount1.add(tokensOwed1); // 计算流动性资产 if (params.tickCurrent < params.tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = amount0.add(uint256( -SqrtPriceMath.getAmount0Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), -int256(liquidity).toInt128() ) )); } else if (params.tickCurrent < params.tickUpper) { // current tick is inside the passed range amount0 = amount0.add(uint256( -SqrtPriceMath.getAmount0Delta( params.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), -int256(liquidity).toInt128() ) )); amount1 = amount1.add(uint256( -SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), params.sqrtPriceX96, -int256(liquidity).toInt128() ) )); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = amount1.add(uint256( -SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), -int256(liquidity).toInt128() ) )); } } /// @notice 封装成结构体的函数调用参数. struct FeeGrowthInsideParams { // 交易对地址 address pool; // The lower tick boundary of the position int24 tickLower; // The upper tick boundary of the position int24 tickUpper; // The current tick int24 tickCurrent; // The all-time global fee growth, per unit of liquidity, in token0 uint256 feeGrowthGlobal0X128; // The all-time global fee growth, per unit of liquidity, in token1 uint256 feeGrowthGlobal1X128; } /// @notice Retrieves fee growth data /// @param params 封装成结构体的函数调用参数. /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside(FeeGrowthInsideParams memory params) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { IUniswapV3Pool _pool = IUniswapV3Pool (params.pool); // calculate fee growth below uint256 lower_feeGrowthOutside0X128; uint256 lower_feeGrowthOutside1X128; ( , , lower_feeGrowthOutside0X128, lower_feeGrowthOutside1X128, , , ,) = _pool.ticks(params.tickLower); uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (params.tickCurrent >= params.tickLower) { feeGrowthBelow0X128 = lower_feeGrowthOutside0X128; feeGrowthBelow1X128 = lower_feeGrowthOutside1X128; } else { feeGrowthBelow0X128 = params.feeGrowthGlobal0X128 - lower_feeGrowthOutside0X128; feeGrowthBelow1X128 = params.feeGrowthGlobal1X128 - lower_feeGrowthOutside1X128; } // calculate fee growth above uint256 upper_feeGrowthOutside0X128; uint256 upper_feeGrowthOutside1X128; ( , , upper_feeGrowthOutside0X128, upper_feeGrowthOutside1X128, , , , ) = _pool.ticks(params.tickUpper); uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (params.tickCurrent < params.tickUpper) { feeGrowthAbove0X128 = upper_feeGrowthOutside0X128; feeGrowthAbove1X128 = upper_feeGrowthOutside1X128; } else { feeGrowthAbove0X128 = params.feeGrowthGlobal0X128 - upper_feeGrowthOutside0X128; feeGrowthAbove1X128 = params.feeGrowthGlobal1X128 - upper_feeGrowthOutside1X128; } feeGrowthInside0X128 = params.feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = params.feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } }
Skips a token + fee element from the buffer and returns the remainder path The swap path return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); }
196,630
./partial_match/1/0x3d72EbC5928315FFfCC98d99840ce37E77785E71/sources/contracts/ERC721A.sol
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+1).toString(), ".json")) : ""; }
3,583,538
// File: @openzeppelin\upgrades\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\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 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; } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin\contracts-ethereum-package\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: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * 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 Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable 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; } // File: contracts\common\Base.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Base is Initializable, Context, Ownable { address constant ZERO_ADDRESS = address(0); function initialize() public initializer { Ownable.initialize(_msgSender()); } } // File: contracts\core\ModuleNames.sol pragma solidity ^0.5.12; /** * @dev List of module names */ contract ModuleNames { // Pool Modules string internal constant MODULE_ACCESS = "access"; string internal constant MODULE_SAVINGS = "savings"; string internal constant MODULE_INVESTING = "investing"; string internal constant MODULE_STAKING_AKRO = "staking"; string internal constant MODULE_STAKING_ADEL = "stakingAdel"; string internal constant MODULE_DCA = "dca"; string internal constant MODULE_REWARD = "reward"; string internal constant MODULE_REWARD_DISTR = "rewardDistributions"; string internal constant MODULE_VAULT = "vault"; // Pool tokens string internal constant TOKEN_AKRO = "akro"; string internal constant TOKEN_ADEL = "adel"; // External Modules (used to store addresses of external contracts) string internal constant CONTRACT_RAY = "ray"; } // File: contracts\common\Module.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Module is Base, ModuleNames { event PoolAddressChanged(address newPool); address public pool; function initialize(address _pool) public initializer { Base.initialize(); setPool(_pool); } function setPool(address _pool) public onlyOwner { require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero"); pool = _pool; emit PoolAddressChanged(_pool); } function getModuleAddress(string memory module) public view returns(address){ require(pool != ZERO_ADDRESS, "Module: no pool"); (bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module)); //Forward error from Pool contract if (!success) assembly { revert(add(result, 32), result) } address moduleAddress = abi.decode(result, (address)); // string memory error = string(abi.encodePacked("Module: requested module not found - ", module)); // require(moduleAddress != ZERO_ADDRESS, error); require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress; } } // File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts\modules\reward\RewardManagerRole.sol pragma solidity ^0.5.12; contract RewardManagerRole is Initializable, Context { using Roles for Roles.Role; event RewardManagerAdded(address indexed account); event RewardManagerRemoved(address indexed account); Roles.Role private _managers; function initialize(address sender) public initializer { if (!isRewardManager(sender)) { _addRewardManager(sender); } } modifier onlyRewardManager() { require(isRewardManager(_msgSender()), "RewardManagerRole: caller does not have the RewardManager role"); _; } function addRewardManager(address account) public onlyRewardManager { _addRewardManager(account); } function renounceRewardManager() public { _removeRewardManager(_msgSender()); } function isRewardManager(address account) public view returns (bool) { return _managers.has(account); } function _addRewardManager(address account) internal { _managers.add(account); emit RewardManagerAdded(account); } function _removeRewardManager(address account) internal { _managers.remove(account); emit RewardManagerRemoved(account); } } // File: contracts\modules\reward\RewardVestingModule.sol pragma solidity ^0.5.12; contract RewardVestingModule is Module, RewardManagerRole { event RewardTokenRegistered(address indexed protocol, address token); event EpochRewardAdded(address indexed protocol, address indexed token, uint256 epoch, uint256 amount); event RewardClaimed(address indexed protocol, address indexed token, uint256 claimPeriodStart, uint256 claimPeriodEnd, uint256 claimAmount); using SafeERC20 for IERC20; using SafeMath for uint256; struct Epoch { uint256 end; // Timestamp of Epoch end uint256 amount; // Amount of reward token for this protocol on this epoch } struct RewardInfo { Epoch[] epochs; uint256 lastClaim; // Timestamp of last claim } struct ProtocolRewards { address[] tokens; mapping(address=>RewardInfo) rewardInfo; } mapping(address => ProtocolRewards) internal rewards; uint256 public defaultEpochLength; function initialize(address _pool) public initializer { Module.initialize(_pool); RewardManagerRole.initialize(_msgSender()); defaultEpochLength = 7*24*60*60; } function getRewardInfo(address protocol, address token) public view returns(uint256 lastClaim, uint256 epochCount) { ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; return (ri.lastClaim, ri.epochs.length); } function registerRewardToken(address protocol, address token, uint256 firstEpochStart) public onlyRewardManager { if(firstEpochStart == 0) firstEpochStart = block.timestamp; //Push zero epoch ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; require(ri.epochs.length == 0, "RewardVesting: token already registered for this protocol"); r.tokens.push(token); ri.epochs.push(Epoch({ end: firstEpochStart, amount: 0 })); emit RewardTokenRegistered(protocol, token); } function setDefaultEpochLength(uint256 _defaultEpochLength) public onlyRewardManager { defaultEpochLength = _defaultEpochLength; } function getEpochInfo(address protocol, address token, uint256 epoch) public view returns(uint256 epochStart, uint256 epochEnd, uint256 rewardAmount) { ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; require(ri.epochs.length > 0, "RewardVesting: protocol or token not registered"); require (epoch < ri.epochs.length, "RewardVesting: epoch number too high"); if(epoch == 0) { epochStart = 0; }else { epochStart = ri.epochs[epoch-1].end; } epochEnd = ri.epochs[epoch].end; rewardAmount = ri.epochs[epoch].amount; return (epochStart, epochEnd, rewardAmount); } function getLastCreatedEpoch(address protocol, address token) public view returns(uint256) { ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; require(ri.epochs.length > 0, "RewardVesting: protocol or token not registered"); return ri.epochs.length-1; } function claimRewards() public { address protocol = _msgSender(); ProtocolRewards storage r = rewards[protocol]; //require(r.tokens.length > 0, "RewardVesting: call only from registered protocols allowed"); if(r.tokens.length == 0) return; //This allows claims from protocols which are not yet registered without reverting for(uint256 i=0; i < r.tokens.length; i++){ _claimRewards(protocol, r.tokens[i]); } } function claimRewards(address protocol, address token) public { _claimRewards(protocol, token); } function _claimRewards(address protocol, address token) internal { ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; uint256 epochsLength = ri.epochs.length; require(epochsLength > 0, "RewardVesting: protocol or token not registered"); Epoch storage lastEpoch = ri.epochs[epochsLength-1]; uint256 previousClaim = ri.lastClaim; if(previousClaim == lastEpoch.end) return; // Nothing to claim yet if(lastEpoch.end < block.timestamp) { ri.lastClaim = lastEpoch.end; }else{ ri.lastClaim = block.timestamp; } uint256 claimAmount; Epoch storage ep = ri.epochs[0]; uint256 i; // Searching for last claimable epoch for(i = epochsLength-1; i > 0; i--) { ep = ri.epochs[i]; if(ep.end < block.timestamp) { // We've found last fully-finished epoch if(i < epochsLength-1) { // We have already started current epoch i++; // Go back to currently-running epoch ep = ri.epochs[i]; } break; } } if(ep.end > block.timestamp) { //Half-claim uint256 epStart = ri.epochs[i-1].end; uint256 claimStart = (previousClaim > epStart)?previousClaim:epStart; uint256 epochClaim = ep.amount.mul(block.timestamp.sub(claimStart)).div(ep.end.sub(epStart)); claimAmount = claimAmount.add(epochClaim); i--; } //Claim rest for(i; i > 0; i--) { ep = ri.epochs[i]; uint256 epStart = ri.epochs[i-1].end; if(ep.end > previousClaim) { if(previousClaim > epStart) { uint256 epochClaim = ep.amount.mul(ep.end.sub(previousClaim)).div(ep.end.sub(epStart)); claimAmount = claimAmount.add(epochClaim); } else { claimAmount = claimAmount.add(ep.amount); } } else { break; } } IERC20(token).safeTransfer(protocol, claimAmount); emit RewardClaimed(protocol, token, previousClaim, ri.lastClaim, claimAmount); } function createEpoch(address protocol, address token, uint256 epochEnd, uint256 amount) public onlyRewardManager { ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; uint256 epochsLength = ri.epochs.length; require(epochsLength > 0, "RewardVesting: protocol or token not registered"); uint256 prevEpochEnd = ri.epochs[epochsLength-1].end; require(epochEnd > prevEpochEnd, "RewardVesting: new epoch should end after previous"); ri.epochs.push(Epoch({ end: epochEnd, amount:0 })); _addReward(protocol, token, epochsLength, amount); } function addReward(address protocol, address token, uint256 epoch, uint256 amount) public onlyRewardManager { _addReward(protocol, token, epoch, amount); } function addRewards(address[] calldata protocols, address[] calldata tokens, uint256[] calldata epochs, uint256[] calldata amounts) external onlyRewardManager { require( (protocols.length == tokens.length) && (protocols.length == epochs.length) && (protocols.length == amounts.length), "RewardVesting: array lengths do not match"); for(uint256 i=0; i<protocols.length; i++) { _addReward(protocols[i], tokens[i], epochs[i], amounts[i]); } } /** * @notice Add reward to existing epoch or crete a new one * @param protocol Protocol for reward * @param token Reward token * @param epoch Epoch number - can be 0 to create new Epoch * @param amount Amount of Reward token to deposit */ function _addReward(address protocol, address token, uint256 epoch, uint256 amount) internal { ProtocolRewards storage r = rewards[protocol]; RewardInfo storage ri = r.rewardInfo[token]; uint256 epochsLength = ri.epochs.length; require(epochsLength > 0, "RewardVesting: protocol or token not registered"); if(epoch == 0) epoch = epochsLength; // creating a new epoch if (epoch == epochsLength) { uint256 epochEnd = ri.epochs[epochsLength-1].end.add(defaultEpochLength); if(epochEnd < block.timestamp) epochEnd = block.timestamp; //This generally should not happen, but just in case - we generate only one epoch since previous end ri.epochs.push(Epoch({ end: epochEnd, amount: amount })); } else { require(epochsLength > epoch, "RewardVesting: epoch is too high"); Epoch storage ep = ri.epochs[epoch]; require(ep.end > block.timestamp, "RewardVesting: epoch already finished"); ep.amount = ep.amount.add(amount); } emit EpochRewardAdded(protocol, token, epoch, amount); IERC20(token).safeTransferFrom(_msgSender(), address(this), amount); } } // File: contracts\modules\staking\IERC900.sol pragma solidity ^0.5.12; /** * @title ERC900 Simple Staking Interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md */ interface IERC900 { event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); function stake(uint256 amount, bytes calldata data) external; function stakeFor(address user, uint256 amount, bytes calldata data) external; function unstake(uint256 amount, bytes calldata data) external; function totalStakedFor(address addr) external view returns (uint256); function totalStaked() external view returns (uint256); function token() external view returns (address); function supportsHistory() external pure returns (bool); // NOTE: Not implementing the optional functions // function lastStakedFor(address addr) external view returns (uint256); // function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); // function totalStakedAt(uint256 blockNumber) external view returns (uint256); } // File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\CapperRole.sol pragma solidity ^0.5.0; contract CapperRole is Initializable, Context { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private _cappers; function initialize(address sender) public initializer { if (!isCapper(sender)) { _addCapper(sender); } } modifier onlyCapper() { require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role"); _; } function isCapper(address account) public view returns (bool) { return _cappers.has(account); } function addCapper(address account) public onlyCapper { _addCapper(account); } function renounceCapper() public { _removeCapper(_msgSender()); } function _addCapper(address account) internal { _cappers.add(account); emit CapperAdded(account); } function _removeCapper(address account) internal { _cappers.remove(account); emit CapperRemoved(account); } uint256[50] private ______gap; } // File: contracts\modules\staking\StakingPoolBase.sol pragma solidity ^0.5.12; /** * @title ERC900 Simple Staking Interface basic implementation * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md */ contract StakingPoolBase is Module, IERC900, CapperRole { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } bool public userCapEnabled; mapping(address => uint256) public userCap; //Limit of pool tokens which can be minted for a user during deposit uint256 public defaultUserCap; bool public stakingCapEnabled; uint256 public stakingCap; bool public vipUserEnabled; mapping(address => bool) public isVipUser; uint256 internal totalStakedAmount; uint256 public coeffScore; event VipUserEnabledChange(bool enabled); event VipUserChanged(address indexed user, bool isVip); event StakingCapChanged(uint256 newCap); event StakingCapEnabledChange(bool enabled); //global cap event DefaultUserCapChanged(uint256 newCap); event UserCapEnabledChange(bool enabled); event UserCapChanged(address indexed user, uint256 newCap); event Staked(address indexed user, uint256 amount, uint256 totalStacked, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 totalStacked, bytes data); event setLockInDuration(uint256 defaultLockInDuration); event CoeffScoreUpdated(uint256 coeff); /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, address(this), _amount), "Stake required"); _; } modifier isUserCapEnabledForStakeFor(uint256 stake) { if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) { require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap"); } if(userCapEnabled) { uint256 cap = userCap[_msgSender()]; //check default user cap settings if (defaultUserCap > 0) { uint256 totalStaked = totalStakedFor(_msgSender()); //get new cap if (defaultUserCap >= totalStaked) { cap = defaultUserCap.sub(totalStaked); } else { cap = 0; } } require(cap >= stake, "StakingModule: stake exeeds cap"); cap = cap.sub(stake); userCap[_msgSender()] = cap; emit UserCapChanged(_msgSender(), cap); } _; } modifier isUserCapEnabledForUnStakeFor(uint256 unStake) { _; checkAndUpdateCapForUnstakeFor(unStake); } function checkAndUpdateCapForUnstakeFor(uint256 unStake) internal { if(userCapEnabled){ uint256 cap = userCap[_msgSender()]; cap = cap.add(unStake); if (cap > defaultUserCap) { cap = defaultUserCap; } userCap[_msgSender()] = cap; emit UserCapChanged(_msgSender(), cap); } } modifier checkUserCapDisabled() { require(isUserCapEnabled() == false, "UserCapEnabled"); _; } modifier checkUserCapEnabled() { require(isUserCapEnabled(), "UserCapDisabled"); _; } function initialize(address _pool, ERC20 _stakingToken, uint256 _defaultLockInDuration) public initializer { stakingToken = _stakingToken; defaultLockInDuration = _defaultLockInDuration; Module.initialize(_pool); CapperRole.initialize(_msgSender()); } function setDefaultLockInDuration(uint256 _defaultLockInDuration) public onlyOwner { defaultLockInDuration = _defaultLockInDuration; emit setLockInDuration(_defaultLockInDuration); } function setUserCapEnabled(bool _userCapEnabled) public onlyCapper { userCapEnabled = _userCapEnabled; emit UserCapEnabledChange(userCapEnabled); } function setStakingCapEnabled(bool _stakingCapEnabled) public onlyCapper { stakingCapEnabled= _stakingCapEnabled; emit StakingCapEnabledChange(stakingCapEnabled); } function setDefaultUserCap(uint256 _newCap) public onlyCapper { defaultUserCap = _newCap; emit DefaultUserCapChanged(_newCap); } function setStakingCap(uint256 _newCap) public onlyCapper { stakingCap = _newCap; emit StakingCapChanged(_newCap); } function setUserCap(address user, uint256 cap) public onlyCapper { userCap[user] = cap; emit UserCapChanged(user, cap); } function setUserCap(address[] memory users, uint256[] memory caps) public onlyCapper { require(users.length == caps.length, "SavingsModule: arrays length not match"); for(uint256 i=0; i < users.length; i++) { userCap[users[i]] = caps[i]; emit UserCapChanged(users[i], caps[i]); } } function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper { vipUserEnabled = _vipUserEnabled; emit VipUserEnabledChange(_vipUserEnabled); } function setVipUser(address user, bool isVip) public onlyCapper { isVipUser[user] = isVip; emit VipUserChanged(user, isVip); } function setCoeffScore(uint256 coeff) public onlyCapper { coeffScore = coeff; emit CoeffScoreUpdated(coeff); } function isUserCapEnabled() public view returns(bool) { return userCapEnabled; } function iStakingCapEnabled() public view returns(bool) { return stakingCapEnabled; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[] memory) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[] memory) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } function getPersonalStakeTotalAmount(address _address) public view returns(uint256) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); uint256 totalStake; for(uint256 i=0; i <actualAmounts.length; i++) { totalStake = totalStake.add(actualAmounts[i]); } return totalStake; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[] memory) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes memory _data) public isUserCapEnabledForStakeFor(_amount) { createStake( _msgSender(), _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes memory _data) public checkUserCapDisabled { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes memory _data) public { withdrawStake( _amount, _data); } // function unstakeAllUnlocked(bytes memory _data) public returns (uint256) { // uint256 unstakeAllAmount = 0; // uint256 personalStakeIndex = stakeHolders[_msgSender()].personalStakeIndex; // for (uint256 i = personalStakeIndex; i < stakeHolders[_msgSender()].personalStakes.length; i++) { // if (stakeHolders[_msgSender()].personalStakes[i].unlockedTimestamp <= block.timestamp) { // unstakeAllAmount = unstakeAllAmount.add(stakeHolders[_msgSender()].personalStakes[i].actualAmount); // withdrawStake(stakeHolders[_msgSender()].personalStakes[i].actualAmount, _data); // } // } // return unstakeAllAmount; // } function unstakeAllUnlocked(bytes memory _data) public returns (uint256) { return withdrawStakes(_msgSender(), _msgSender(), _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalScoresFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor.mul(coeffScore).div(10**18); } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { //return stakingToken.balanceOf(address(this)); return totalStakedAmount; } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return address(stakingToken); } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[] memory, uint256[] memory, address[] memory) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes memory _data) internal canStake(_msgSender(), _amount) { if (!stakeHolders[_msgSender()].exists) { stakeHolders[_msgSender()].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[_msgSender()].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); totalStakedAmount = totalStakedAmount.add(_amount); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the _msgSender() * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes memory _data) internal isUserCapEnabledForUnStakeFor(_amount) { Stake storage personalStake = stakeHolders[_msgSender()].personalStakes[stakeHolders[_msgSender()].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(_msgSender(), _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[_msgSender()].personalStakeIndex++; totalStakedAmount = totalStakedAmount.sub(_amount); emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } function withdrawStakes(address _transferTo, address _unstakeFor, bytes memory _data) internal returns (uint256){ StakeContract storage sc = stakeHolders[_unstakeFor]; uint256 unstakeAmount = 0; uint256 unstakedForOthers = 0; uint256 personalStakeIndex = sc.personalStakeIndex; uint256 i; for (i = personalStakeIndex; i < sc.personalStakes.length; i++) { Stake storage personalStake = sc.personalStakes[i]; if(personalStake.unlockedTimestamp > block.timestamp) break; //We've found last unlocked stake if(personalStake.stakedFor != _unstakeFor){ //Handle unstake of staked for other address stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor].totalStakedFor.sub(personalStake.actualAmount); unstakedForOthers = unstakedForOthers.add(personalStake.actualAmount); emit Unstaked(personalStake.stakedFor, personalStake.actualAmount, totalStakedFor(personalStake.stakedFor), _data); } unstakeAmount = unstakeAmount.add(personalStake.actualAmount); personalStake.actualAmount = 0; } sc.personalStakeIndex = i; uint256 unstakedForSender = unstakeAmount.sub(unstakedForOthers); sc.totalStakedFor = sc.totalStakedFor.sub(unstakedForSender); totalStakedAmount = totalStakedAmount.sub(unstakeAmount); require(stakingToken.transfer(_transferTo, unstakeAmount), "Unable to withdraw"); emit Unstaked(_unstakeFor, unstakedForSender, sc.totalStakedFor, _data); checkAndUpdateCapForUnstakeFor(unstakeAmount); return unstakeAmount; } uint256[49] private ______gap; } // File: contracts\modules\staking\StakingPool.sol pragma solidity ^0.5.12; contract StakingPool is StakingPoolBase { event RewardTokenRegistered(address token); event RewardDistributionCreated(address token, uint256 amount, uint256 totalShares); event RewardWithdraw(address indexed user, address indexed rewardToken, uint256 amount); using SafeERC20 for IERC20; using SafeMath for uint256; struct RewardDistribution { uint256 totalShares; uint256 amount; } struct UserRewardInfo { mapping(address=>uint256) nextDistribution; //Next unclaimed distribution } struct RewardData { RewardDistribution[] distributions; uint256 unclaimed; } RewardVestingModule public rewardVesting; address[] internal registeredRewardTokens; mapping(address=>RewardData) internal rewards; mapping(address=>UserRewardInfo) internal userRewards; address public swapContract; modifier onlyRewardDistributionModule() { require(_msgSender() == getModuleAddress(MODULE_REWARD_DISTR), "StakingPool: calls allowed from RewardDistributionModule only"); _; } function setRewardVesting(address _rewardVesting) public onlyOwner { rewardVesting = RewardVestingModule(_rewardVesting); } function registerRewardToken(address token) public onlyOwner { require(!isRegisteredRewardToken(token), "StakingPool: already registered"); registeredRewardTokens.push(token); emit RewardTokenRegistered(token); } function claimRewardsFromVesting() public onlyCapper{ _claimRewardsFromVesting(); } function isRegisteredRewardToken(address token) public view returns(bool) { for(uint256 i=0; i<registeredRewardTokens.length; i++){ if(token == registeredRewardTokens[i]) return true; } return false; } function supportedRewardTokens() public view returns(address[] memory) { return registeredRewardTokens; } function withdrawRewards() public returns(uint256[] memory){ return _withdrawRewards(_msgSender()); } function withdrawRewardsFor(address user, address rewardToken) public onlyRewardDistributionModule returns(uint256) { return _withdrawRewards(user, rewardToken); } // function withdrawRewardsFor(address user, address[] memory rewardTokens) onlyRewardDistributionModule { // for(uint256 i=0; i < rewardTokens.length; i++) { // _withdrawRewards(user, rewardTokens[i]); // } // } function rewardBalanceOf(address user, address token) public view returns(uint256) { RewardData storage rd = rewards[token]; if(rd.unclaimed == 0) return 0; //Either token not registered or everything is already claimed uint256 shares = getPersonalStakeTotalAmount(user); if(shares == 0) return 0; UserRewardInfo storage uri = userRewards[user]; uint256 reward; for(uint256 i=uri.nextDistribution[token]; i < rd.distributions.length; i++) { RewardDistribution storage rdistr = rd.distributions[i]; uint256 r = shares.mul(rdistr.amount).div(rdistr.totalShares); reward = reward.add(r); } return reward; } function _withdrawRewards(address user) internal returns(uint256[] memory rwrds) { rwrds = new uint256[](registeredRewardTokens.length); for(uint256 i=0; i<registeredRewardTokens.length; i++){ rwrds[i] = _withdrawRewards(user, registeredRewardTokens[i]); } return rwrds; } function _withdrawRewards(address user, address token) internal returns(uint256){ UserRewardInfo storage uri = userRewards[user]; RewardData storage rd = rewards[token]; if(rd.distributions.length == 0) { //No distributions = nothing to do return 0; } uint256 rwrds = rewardBalanceOf(user, token); uri.nextDistribution[token] = rd.distributions.length; if(rwrds > 0){ rewards[token].unclaimed = rewards[token].unclaimed.sub(rwrds); IERC20(token).transfer(user, rwrds); emit RewardWithdraw(user, token, rwrds); } return rwrds; } function createStake(address _address, uint256 _amount, uint256 _lockInDuration, bytes memory _data) internal { _withdrawRewards(_address); super.createStake(_address, _amount, _lockInDuration, _data); } function unstake(uint256 _amount, bytes memory _data) public { _withdrawRewards(_msgSender()); withdrawStake(_amount, _data); } function unstakeAllUnlocked(bytes memory _data) public returns (uint256) { _withdrawRewards(_msgSender()); return super.unstakeAllUnlocked(_data); } function _claimRewardsFromVesting() internal { rewardVesting.claimRewards(); for(uint256 i=0; i < registeredRewardTokens.length; i++){ address rt = registeredRewardTokens[i]; uint256 expectedBalance = rewards[rt].unclaimed; if(rt == address(stakingToken)){ expectedBalance = expectedBalance.add(totalStaked()); } uint256 actualBalance = IERC20(rt).balanceOf(address(this)); uint256 distributionAmount = actualBalance.sub(expectedBalance); if(actualBalance > expectedBalance) { uint256 totalShares = totalStaked(); rewards[rt].distributions.push(RewardDistribution({ totalShares: totalShares, amount: distributionAmount })); rewards[rt].unclaimed = rewards[rt].unclaimed.add(distributionAmount); emit RewardDistributionCreated(rt, distributionAmount, totalShares); } } } modifier swapEligible(address _user) { require(swapContract != address(0), "Swap is disabled"); require(_msgSender() == swapContract, "Caller is not a swap contract"); require(_user != address(0), "Zero address"); _; } /** * @notice Admin function to set the address of the ADEL/vAkro Swap contract * @notice Default value is 0-address, which means, that swap is disabled * @param _swapContract Adel to vAkro Swap contract. */ function setSwapContract(address _swapContract) external onlyOwner { swapContract = _swapContract; } /** * @notice Function which is alternative to "unstake" the ADEL token. * @notice Though, instead of withdrawing the ADEL, the function sends it to the Swap contract. * @notice Can be called ONLY by the Swap contract. * @param _user User to withdraw the stake for. * @param _token Adel address. * @param _data Data for the event. */ function withdrawStakeForSwap(address _user, address _token, bytes calldata _data) external swapEligible(_user) returns(uint256) { uint256 returnValue = 0; for(uint256 i = 0; i < registeredRewardTokens.length; i++) { uint256 rwrds = withdrawRewardForSwap(_user, registeredRewardTokens[i]); if (_token == registeredRewardTokens[i]) { returnValue += rwrds; } } return returnValue + super.withdrawStakes(_msgSender(), _user, _data); } /** * @notice Function which is alternative to "claiming" ADEL rewards. * @notice Though, instead of claiming the ADEL, the function sends it to the Swap contract. * @notice Can be called ONLY by the Swap contract. * @param _user User to withdraw the stake for. * @param _token Token to get the rewards (can be only ADEL). */ function withdrawRewardForSwap(address _user, address _token) public swapEligible(_user) returns(uint256) { UserRewardInfo storage uri = userRewards[_user]; RewardData storage rd = rewards[_token]; require(rd.distributions.length > 0, "No distributions"); //No distributions = nothing to do uint256 rwrds = rewardBalanceOf(_user, _token); if (rwrds == 0) { return 0; } uri.nextDistribution[_token] = rd.distributions.length; rewards[_token].unclaimed = rewards[_token].unclaimed.sub(rwrds); IERC20(_token).transfer(swapContract, rwrds); emit RewardWithdraw(_user, _token, rwrds); return rwrds; } } // File: contracts\deploy\StakingPoolADEL.sol pragma solidity ^0.5.12; contract StakingPoolADEL is StakingPool { }
Returns the current total of tokens staked for an address _address address The address to query return uint256 The number of tokens staked for the given address/
function totalScoresFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor.mul(coeffScore).div(10**18); }
7,023,433
/* Copyright (C) 2021 Soteria.fund 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/ */ pragma solidity ^0.5.17; import "./external/Governed.sol"; import "./external/OwnedUpgradeabilityProxy.sol"; import "../../libraries/SafeMath.sol"; import "../claims/Claims.sol"; import "../capital/Pool2.sol"; import "../cover/Quotation.sol"; import "./MemberRoles.sol"; contract SOTEMaster is Governed { using SafeMath for uint; struct EmergencyPause { bool pause; uint time; bytes4 by; } EmergencyPause[] public emergencyPaused; bytes2[] internal allContractNames; mapping(address => bool) public contractsActive; mapping(bytes2 => address payable) internal allContractVersions; mapping(bytes2 => bool) public isProxy; mapping(bytes2 => bool) public isUpgradable; address public tokenAddress; bool internal reentrancyLock; bool public masterInitialized; address public owner; uint public pauseTime; bool constructorCheck; modifier noReentrancy() { require(!reentrancyLock, "Reentrant call."); reentrancyLock = true; _; reentrancyLock = false; } /// @dev to initiate master data /// @param _tokenAdd SOTE token address. function initiateMaster(address _tokenAdd,address payable _govAdd) external { OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(address(uint160(address(this)))); require(msg.sender == proxy.proxyOwner(),"Sender is not proxy owner."); require(!constructorCheck,"Constructor already ran."); constructorCheck = true; tokenAddress = _tokenAdd; owner = msg.sender; masterAddress = address(this); contractsActive[address(this)] = true; pauseTime = 28 days; //4 weeks // 1. init gov allContractNames.push("GV"); allContractVersions["GV"] = _govAdd; contractsActive[_govAdd] = true; isProxy["GV"] = true; // 2. set masterInitialized masterInitialized = true; } function upgradeMultipleImplementations( bytes2[] calldata _contractNames, address[] calldata _contractAddresses ) external onlyAuthorizedToGovern { require(_contractNames.length == _contractAddresses.length,"Array length should be equal."); for (uint i=0; i < _contractNames.length; i++) { require(_contractAddresses[i] != address(0),"null address is not allowed."); require(isProxy[_contractNames[i]],"Contract should be proxy."); OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(allContractVersions[_contractNames[i]]); proxy.upgradeTo(_contractAddresses[i]); } } /// @dev Adds new internal contract /// @param _type pass 1 if contract is upgradable, 2 if contract is proxy, any other uint if none. function addNewInternalContract( bytes2 _contractName, address payable _contractAddress, uint _type ) external onlyAuthorizedToGovern { require(allContractVersions[_contractName] == address(0),"Contract code is already available."); require(_contractAddress != address(0),"NULL address is not allowed."); allContractNames.push(_contractName); address newInternalContract = _contractAddress; // Using extra varible to get rid of if condition. if (_type == 1) { isUpgradable[_contractName] = true; } else if (_type == 2) { newInternalContract = _generateProxy(_contractAddress); isProxy[_contractName] = true; } allContractVersions[_contractName] = address(uint160(newInternalContract)); contractsActive[newInternalContract] = true; Iupgradable up = Iupgradable(allContractVersions[_contractName]); up.changeMasterAddress(address(this)); up.changeDependentContractAddress(); } /** * @dev Anyone can close a claim if oraclize fails to close it. * @param _claimId id of claim to be closed. */ function closeClaim(uint _claimId) external { require(canCall(_claimId), "Payout retry time not reached."); ClaimsReward cr = ClaimsReward(getLatestAddress("CR")); cr.changeClaimStatus(_claimId); } /** * @dev Handles the oraclize query callback. * @param myid ID of oraclize query to be processed */ function delegateCallBack(bytes32 myid) external noReentrancy { PoolData pd = PoolData(getLatestAddress("PD")); uint callTime = pd.getDateUpdOfAPI(myid); uint dateAdd = pd.getDateAddOfAPI(myid); require(callTime == dateAdd, "Callback already received"); bytes4 res = pd.getApiIdTypeOf(myid); pd.updateDateUpdOfAPI(myid); if (isPause()) { bytes4 by; (, , by) = getLastEmergencyPause(); require(res == "EP", "Only callback of type EP is allowed during emergency pause"); require(callTime.add(pauseTime) < now, "Callback was called too soon"); require(by == "AB", "Emergency paused was not started by Advisory Board"); addEmergencyPause(false, "AUT"); return; } uint id = pd.getIdOfApiId(myid); if (res == "COV") { Quotation qt = Quotation(getLatestAddress("QT")); qt.expireCover(id); return; } if (res == "CLA") { require(canCall(id), "Payout retry time not reached"); ClaimsReward cr = ClaimsReward(getLatestAddress("CR")); cr.changeClaimStatus(id); return; } if (res == "MCRF") { require(callTime.add(pd.mcrFailTime()) < now, "MCR posting time not reached"); MCR m1 = MCR(getLatestAddress("MC")); m1.addLastMCRData(uint64(id)); return; } if (res == "ULT") { require(callTime.add(pd.liquidityTradeCallbackTime()) < now, "Liquidity trade time not reached"); Pool2 p2 = Pool2(getLatestAddress("P2")); p2.externalLiquidityTrade(); return; } if (res == "MCR" || res == "IARB") { return; } revert("Invalid callback"); } function getOwnerParameters(bytes8 code) external view returns(bytes8 codeVal, address val) { codeVal = code; QuotationData qd; PoolData pd; if (code == "MSWALLET") { TokenData td; td = TokenData(getLatestAddress("TD")); val = td.walletAddress(); } else if (code == "MCRNOTA") { pd = PoolData(getLatestAddress("PD")); val = pd.notariseMCR(); } else if (code == "DAIFEED") { pd = PoolData(getLatestAddress("PD")); val = pd.daiFeedAddress(); } else if (code == "UNISWADD") { Pool2 p2; p2 = Pool2(getLatestAddress("P2")); val = p2.uniswapFactoryAddress(); } else if (code == "OWNER") { val = owner; } else if (code == "QUOAUTH") { qd = QuotationData(getLatestAddress("QD")); val = qd.authQuoteEngine(); } else if (code == "KYCAUTH") { qd = QuotationData(getLatestAddress("QD")); val = qd.kycAuthAddress(); } } /// @dev Add Emergency pause /// @param _pause to set Emergency Pause ON/OFF /// @param _by to set who Start/Stop EP function addEmergencyPause(bool _pause, bytes4 _by) public { require(_by == "AB" || _by == "AUT","Invalid call."); require(msg.sender == getLatestAddress("P1") || msg.sender == getLatestAddress("GV"),"Callable by P1 and GV only."); emergencyPaused.push(EmergencyPause(_pause, now, _by)); if (_pause == false) { Claims c1 = Claims(allContractVersions["CL"]); c1.submitClaimAfterEPOff(); // Process claims submitted while EP was on c1.startAllPendingClaimsVoting(); // Resume voting on all pending claims } } ///@dev update time in seconds for which emergency pause is applied. function updatePauseTime(uint _time) public { require(isInternal(msg.sender),"Not internal call."); pauseTime = _time; } /// @dev upgrades All Address at a time function upgradeAllAddress() public onlyAuthorizedToGovern { _changeAllAddress(); } function changeAllAddress(uint8 start,uint8 end) public { uint i; for (i = start; i < end; i++) { contractsActive[allContractVersions[allContractNames[i]]] = true; Iupgradable up = Iupgradable(allContractVersions[allContractNames[i]]); up.changeDependentContractAddress(); } } /// @dev upgrades contract at a time function upgradeContract( bytes2 _contractsName, address payable _contractsAddress ) public onlyAuthorizedToGovern { address payable oldAddress = allContractVersions[_contractsName]; contractsActive[oldAddress] = false; allContractVersions[_contractsName] = _contractsAddress; contractsActive[_contractsAddress] = true; Iupgradable up = Iupgradable(allContractVersions[_contractsName]); up.changeMasterAddress(address(this)); } /// @dev upgrades multiple contracts at a time function upgradeMultipleContracts( bytes2[] memory _contractsName, address payable[] memory _contractsAddress ) public onlyAuthorizedToGovern { require(_contractsName.length == _contractsAddress.length, "Array length should be equal."); for (uint i=0; i<_contractsName.length; i++) { address payable newAddress = _contractsAddress[i]; require(newAddress != address(0),"NULL address is not allowed."); require(isUpgradable[_contractsName[i]],"Contract should be upgradable."); if (_contractsName[i] == "QT") { Quotation qt = Quotation(allContractVersions["QT"]); qt.transferAssetsToNewContract(newAddress); } else if (_contractsName[i] == "CR") { TokenController tc = TokenController(getLatestAddress("TC")); tc.addToWhitelist(newAddress); tc.removeFromWhitelist(allContractVersions["CR"]); ClaimsReward cr = ClaimsReward(allContractVersions["CR"]); cr.upgrade(newAddress); } else if (_contractsName[i] == "P1") { Pool1 p1 = Pool1(allContractVersions["P1"]); p1.upgradeCapitalPool(newAddress); } else if (_contractsName[i] == "P2") { Pool2 p2 = Pool2(allContractVersions["P2"]); p2.upgradeInvestmentPool(newAddress); } address payable oldAddress = allContractVersions[_contractsName[i]]; contractsActive[oldAddress] = false; allContractVersions[_contractsName[i]] = newAddress; contractsActive[newAddress] = true; Iupgradable up = Iupgradable(allContractVersions[_contractsName[i]]); up.changeMasterAddress(address(this)); } _changeAllAddress(); } /// @dev checks whether the address is an internal contract address. function isInternal(address _contractAddress) public view returns(bool) { return contractsActive[_contractAddress]; } /// @dev checks whether the address is the Owner or not. function isOwner(address _address) public view returns(bool) { return owner == _address; } /// @dev Checks whether emergency pause id on/not. function isPause() public view returns(bool) { uint length = emergencyPaused.length; return length > 0 && emergencyPaused[length - 1].pause; } /// @dev checks whether the address is a member of the mutual or not. function isMember(address _add) public view returns(bool) { MemberRoles mr = MemberRoles(getLatestAddress("MR")); return mr.checkRole(_add, uint(MemberRoles.Role.Member)); } ///@dev Gets the number of emergency pause has been toggled. function getEmergencyPausedLength() public view returns(uint len) { len = emergencyPaused.length; } ///@dev Gets last emergency pause details. function getLastEmergencyPause() public view returns(bool _pause, uint _time, bytes4 _by) { _pause = false; _time = 0; _by = ""; uint len = getEmergencyPausedLength(); if (len > 0) { len = len.sub(1); _pause = emergencyPaused[len].pause; _time = emergencyPaused[len].time; _by = emergencyPaused[len].by; } } /// @dev Gets latest version name and address /// @return contractsName Latest version's contract names /// @return contractsAddress Latest version's contract addresses function getVersionData() public view returns ( bytes2[] memory contractsName, address[] memory contractsAddress ) { contractsName = allContractNames; contractsAddress = new address[](allContractNames.length); for (uint i = 0; i < allContractNames.length; i++) { contractsAddress[i] = allContractVersions[allContractNames[i]]; } } /** * @dev returns the address of token controller * @return address is returned */ function dAppLocker() public view returns(address _add) { _add = getLatestAddress("TC"); } /** * @dev returns the address of sote token * @return address is returned */ function dAppToken() public view returns(address _add) { _add = tokenAddress; } /// @dev Gets latest contract address /// @param _contractName Contract name to fetch function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress) { contractAddress = allContractVersions[_contractName]; } /// @dev Creates a new version of contract addresses /// @param _contractAddresses Array of contract addresses which will be generated function addNewVersion(address payable[] memory _contractAddresses) public { require(msg.sender == owner && !masterInitialized,"Caller should be owner and should only be called once."); require(_contractAddresses.length == allContractNames.length, "array length not same"); masterInitialized = true; MemberRoles mr = MemberRoles(_contractAddresses[14]); // shoud send proxy address for proxy contracts (if not 1st time deploying) // bool isMasterUpgrade = mr.soteMasterAddress() != address(0); for (uint i = 0; i < allContractNames.length; i++) { require(_contractAddresses[i] != address(0),"NULL address is not allowed."); allContractVersions[allContractNames[i]] = _contractAddresses[i]; contractsActive[_contractAddresses[i]] = true; } // Need to override owner as owner in MR to avoid inconsistency as owner in MR is some other address. (, address[] memory mrOwner) = mr.members(uint(MemberRoles.Role.Owner)); owner = mrOwner[0]; } /** * @dev to check if the address is authorized to govern or not * @param _add is the address in concern * @return the boolean status status for the check */ function checkIsAuthToGoverned(address _add) public view returns(bool) { return isAuthorizedToGovern(_add); } /// @dev Allow AB Members to Start Emergency Pause function startEmergencyPause() public onlyAuthorizedToGovern { addEmergencyPause(true, "AB"); //Start Emergency Pause Pool1 p1 = Pool1(allContractVersions["P1"]); p1.closeEmergencyPause(pauseTime); //oraclize callback of 4 weeks Claims c1 = Claims(allContractVersions["CL"]); c1.pauseAllPendingClaimsVoting(); //Pause Voting of all pending Claims } /** * @dev to update the owner parameters * @param code is the associated code * @param val is value to be set */ function updateOwnerParameters(bytes8 code, address payable val) public onlyAuthorizedToGovern { QuotationData qd; PoolData pd; if (code == "MSWALLET") { TokenData td; td = TokenData(getLatestAddress("TD")); td.changeWalletAddress(val); } else if (code == "MCRNOTA") { pd = PoolData(getLatestAddress("PD")); pd.changeNotariseAddress(val); } else if (code == "DAIFEED") { pd = PoolData(getLatestAddress("PD")); pd.changeDAIfeedAddress(val); } else if (code == "UNISWADD") { Pool2 p2; p2 = Pool2(getLatestAddress("P2")); p2.changeUniswapFactoryAddress(val); } else if (code == "OWNER") { MemberRoles mr = MemberRoles(getLatestAddress("MR")); mr.swapOwner(val); owner = val; } else if (code == "QUOAUTH") { qd = QuotationData(getLatestAddress("QD")); qd.changeAuthQuoteEngine(val); } else if (code == "KYCAUTH") { qd = QuotationData(getLatestAddress("QD")); qd.setKycAuthAddress(val); } else { revert("Invalid param code"); } } /** * @dev to generater proxy * @param _implementationAddress of the proxy */ function _generateProxy(address _implementationAddress) internal returns(address) { OwnedUpgradeabilityProxy proxy = new OwnedUpgradeabilityProxy(_implementationAddress); return address(proxy); } /// @dev Sets the older versions of contract addresses as inactive and the latest one as active. function _changeAllAddress() internal { uint i; for (i = 0; i < allContractNames.length; i++) { contractsActive[allContractVersions[allContractNames[i]]] = true; Iupgradable up = Iupgradable(allContractVersions[allContractNames[i]]); up.changeDependentContractAddress(); } } function canCall(uint _claimId) internal view returns(bool) { ClaimsData cd = ClaimsData(getLatestAddress("CD")); (, , , uint status, uint dateUpd, ) = cd.getClaim(_claimId); if (status == 12) { if (dateUpd.add(cd.payoutRetryTime()) > now) { return false; } } return true; } }
to generater proxy _implementationAddress of the proxy/
function _generateProxy(address _implementationAddress) internal returns(address) { OwnedUpgradeabilityProxy proxy = new OwnedUpgradeabilityProxy(_implementationAddress); return address(proxy); }
7,293,445
./partial_match/1/0x72df14329E29F00A3866794F82723c85c6B36dCC/sources/Debt.sol
Destroy the contract/
function Destroy() public onlyOwner returns (bool) { selfdestruct(msg.sender); return true; }
2,602,015
./partial_match/1/0x5e39B70446b04451e55298eC24dce520425704BD/sources/Controller.sol
某个币对应一个策略,比如现在的ycrv就是挖 yfii
function setStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); address _current = strategies[_token]; Strategy(_current).withdrawAll(); } strategies[_token] = _strategy;
4,044,562
//Address: 0x333b20d643b58263e1558de655fda9cf7d07c401 //Contract name: BitLumensCrowdsale //Balance: 0.01351990855565312 Ether //Verification Date: 5/30/2018 //Transacion Count: 161 // CODE STARTS HERE /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Parse a floating point number from String to uint, e.g. "250.56" to "25056" */ function parse(string s) internal constant returns (uint256) { bytes memory b = bytes(s); uint result = 0; for (uint i = 0; i < b.length; i++) { if (b[i] >= 48 && b[i] <= 57) { result = result * 10 + (uint(b[i]) - 48); } } return result; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BLS is MintableToken { using SafeMath for uint256; string public name = "BLS Token"; string public symbol = "BLS"; uint8 public decimals = 18; bool public enableTransfers = false; // functions overrides in order to maintain the token locked during the ICO function transfer(address _to, uint256 _value) public returns(bool) { require(enableTransfers); return super.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(enableTransfers); return super.transferFrom(_from,_to,_value); } function approve(address _spender, uint256 _value) public returns (bool) { require(enableTransfers); return super.approve(_spender,_value); } /* function burn(uint256 _value) public { require(enableTransfers); super.burn(_value); } */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { require(enableTransfers); super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { require(enableTransfers); super.decreaseApproval(_spender, _subtractedValue); } // enable token transfers function enableTokenTransfers() public onlyOwner { enableTransfers = true; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract ICOEngineInterface { // false if the ico is not started, true if the ico is started and running, true if the ico is completed function started() public view returns(bool); // false if the ico is not started, false if the ico is started and running, true if the ico is completed function ended() public view returns(bool); // time stamp of the starting time of the ico, must return 0 if it depends on the block number function startTime() public view returns(uint); // time stamp of the ending time of the ico, must retrun 0 if it depends on the block number function endTime() public view returns(uint); // Optional function, can be implemented in place of startTime // Returns the starting block number of the ico, must return 0 if it depends on the time stamp // function startBlock() public view returns(uint); // Optional function, can be implemented in place of endTime // Returns theending block number of the ico, must retrun 0 if it depends on the time stamp // function endBlock() public view returns(uint); // returns the total number of the tokens available for the sale, must not change when the ico is started function totalTokens() public view returns(uint); // returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(), // then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens() function remainingTokens() public view returns(uint); // return the price as number of tokens released for each ether function price() public view returns(uint); } // Abstract base contract contract KYCBase { using SafeMath for uint256; mapping (address => bool) public isKycSigner; mapping (uint64 => uint256) public alreadyPayed; event KycVerified(address indexed signer, address buyerAddress, uint64 buyerId, uint maxAmount); function KYCBase(address [] kycSigners) internal { for (uint i = 0; i < kycSigners.length; i++) { isKycSigner[kycSigners[i]] = true; } } // Must be implemented in descending contract to assign tokens to the buyers. Called after the KYC verification is passed function releaseTokensTo(address buyer) internal returns(bool); // This method can be overridden to enable some sender to buy token for a different address function senderAllowedFor(address buyer) internal view returns(bool) { return buyer == msg.sender; } function buyTokensFor(address buyerAddress, uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) public payable returns (bool) { require(senderAllowedFor(buyerAddress)); return buyImplementation(buyerAddress, buyerId, maxAmount, v, r, s); } function buyTokens(uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) public payable returns (bool) { return buyImplementation(msg.sender, buyerId, maxAmount, v, r, s); } function buyImplementation(address buyerAddress, uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) private returns (bool) { // check the signature bytes32 hash = sha256("Eidoo icoengine authorization", this, buyerAddress, buyerId, maxAmount); address signer = ecrecover(hash, v, r, s); if (!isKycSigner[signer]) { revert(); } else { uint256 totalPayed = alreadyPayed[buyerId].add(msg.value); require(totalPayed <= maxAmount); alreadyPayed[buyerId] = totalPayed; KycVerified(signer, buyerAddress, buyerId, maxAmount); return releaseTokensTo(buyerAddress); } } // No payable fallback function, the tokens must be buyed using the functions buyTokens and buyTokensFor function () public { revert(); } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //pragma solidity >=0.4.1 <=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint capacity) internal constant { if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private constant { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private constant returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Reverts if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal constant returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal constant { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Reverts if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal constant returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function shl8(uint8 x, uint8 y) private constant returns (uint8) { return x * (2 ** y); } function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant { if(value <= 23) { buf.append(uint8(shl8(major, 5) | value)); } else if(value <= 0xFF) { buf.append(uint8(shl8(major, 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8(shl8(major, 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant { buf.append(uint8(shl8(major, 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal constant { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal constant { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal constant { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal constant { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> contract BitLumensCrowdsale is Ownable, ICOEngineInterface, KYCBase,usingOraclize { using SafeMath for uint; enum State {Running,Success,Failure} // Current ETH/USD exchange rate uint256 public ETH_USD_EXCHANGE_CENTS= 500;// must be set by orcalize // Everything oraclize related event updatedPrice(string price); event newOraclizeQuery(string description); uint public oraclizeQueryCost; uint public etherPriceUSD; event Log(string text); uint public USD_SOFT_CAP; uint public USD_HARD_CAP; uint public BLS_TOTAL_CAP; uint public BLS_PRE_ICO; State public state; BLS public token; address public wallet; address bitlumensAccount= 0x40d41c859016ec561891526334881326f429b513; address teamAccount= 0xdf71b93617e5197cee3b9ad7ad05934467f95f44; address bountyAccount= 0x1b7b2c0a8d0032de88910f7ff5838f5f35bc9537; // from ICOEngineInterface uint public startTime; uint public endTime; // Time Rounds for ICO uint public roundTwoTime; uint public roundThreeTime; uint public roundFourTime; uint public roundFiveTime; // Discount multipliers , we will divide by 10 later -- divede by 10 later uint public constant TOKEN_FIRST_PRICE_RATE = 20; uint public constant TOKEN_SECOND_PRICE_RATE = 15; uint public constant TOKEN_THIRD_PRICE_RATE = 14; uint public constant TOKEN_FOURTH_PRICE_RATE = 13; uint public constant TOKEN_FIFTH_PRICE_RATE = 12; // to track if team members already got their tokens bool public teamTokensDelivered = false; bool public bountyDelivered = false; bool public bitlumensDelivered = false; // from ICOEngineInterface uint public remainingTokens; // from ICOEngineInterface uint public totalTokens; // amount of wei raised uint public weiRaised; //amount of $$ raised uint public dollarRaised; // boolean to make sure preallocate is called only once bool public isPreallocated; // vault for refunding RefundVault public vault; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the token * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /* event for ICO successfully finalized */ event FinalizedOK(); /* event for ICO not successfully finalized */ event FinalizedNOK(); /** * event for additional token minting * @param to who got the tokens * @param amount amount of tokens purchased */ event Preallocated(address indexed to, uint256 amount); /** * Constructor */ function BitLumensCrowdsale( address [] kycSigner, address _token, address _wallet, uint _startTime, uint _roundTwoTime, uint _roundThreeTime, uint _roundFourTime, uint _roundFiveTime, uint _endTime, uint _BlsPreIco, uint _blsTotalCap, uint _softCapUsd, uint _hardCapUsd, uint _ethUsdExchangeCents ) public payable KYCBase(kycSigner) { require(_token != address(0)); require(_wallet != address(0)); require(bitlumensAccount != address(0)); require(teamAccount != address(0)); require(bountyAccount != address(0)); //please make sure that the start in 3)depoly_tokenSale is larger than now before migrate require(_startTime > now); require (_startTime < _roundTwoTime); require (_roundTwoTime < _roundThreeTime); require (_roundThreeTime < _roundFourTime); require (_roundFourTime < _roundFiveTime); require (_roundFiveTime < _endTime); // OAR = OraclizeAddrResolverI(0xDD6CdC488799a0C6ABF7339f7FBFbb9B8C7C84f6); token = BLS(_token); wallet = _wallet; startTime = _startTime; endTime = _endTime; roundTwoTime= _roundTwoTime; roundThreeTime= _roundThreeTime; roundFourTime= _roundFourTime; roundFiveTime= _roundFiveTime; ETH_USD_EXCHANGE_CENTS = _ethUsdExchangeCents; USD_SOFT_CAP = _softCapUsd; USD_HARD_CAP = _hardCapUsd; BLS_PRE_ICO = _BlsPreIco; BLS_TOTAL_CAP = _blsTotalCap; totalTokens = _blsTotalCap; remainingTokens = _blsTotalCap; vault = new RefundVault(_wallet); state = State.Running; oraclize_setCustomGasPrice(100000000000 wei); // set the gas price a little bit higher, so the pricefeed definitely works updatePrice(); oraclizeQueryCost = oraclize_getPrice("URL"); } /// oraclize START // @dev oraclize is called recursively here - once a callback fetches the newest ETH price, the next callback is scheduled for the next hour again function __callback(bytes32 myid, string result) { require(msg.sender == oraclize_cbAddress()); // setting the token price here ETH_USD_EXCHANGE_CENTS = SafeMath.parse(result); updatedPrice(result); // fetch the next price updatePrice(); } function updatePrice() payable { // can be left public as a way for replenishing contract's ETH balance, just in case if (msg.sender != oraclize_cbAddress()) { require(msg.value >= 200 finney); } if (oraclize_getPrice("URL") > this.balance) { newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { newOraclizeQuery("Oraclize sent, wait.."); // Schedule query in 1 hour. Set the gas amount to 220000, as parsing in __callback takes around 70000 - we play it safe. //the time will be changed to higher value in real network(60 - > 3600 ) oraclize_query(86400, "URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD", 220000); } } //// oraclize END // function that is called from KYCBase function releaseTokensTo(address buyer) internal returns(bool) { // needs to be started require(started()); require(!ended()); //get the amount send in wei uint256 weiAmount = msg.value; uint256 WeiDollars = weiAmount.mul(ETH_USD_EXCHANGE_CENTS); // ammount of dollars X 1e18 (1token) WeiDollars = WeiDollars.div(100); //calculating number of tokens x 10 to prevent decemil uint256 currentPrice = price(); uint tokens = WeiDollars.mul(currentPrice); //fix the number of tokens tokens = tokens.div(10); //calculate tokens Raised by subtracting total tokens from remaining tokens uint tokenRaised = totalTokens.sub(remainingTokens) ; // check if total token raised + the tokens calculated for investor <= (pre ico token limit) if(now < roundTwoTime ){ require(tokenRaised.add(tokens) <= BLS_PRE_ICO); } //check if total token raised + the tokens calculated for investor <= (total token cap) require(tokenRaised.add(tokens) <= BLS_TOTAL_CAP); //check if hard cap is reached weiRaised = weiRaised.add(weiAmount); // total usd in wallet uint centsWeiRaised = weiRaised.mul(ETH_USD_EXCHANGE_CENTS); uint goal = USD_HARD_CAP * (10**18) * (10**2); // if 25,000,000 $$ raised stop the ico require(centsWeiRaised <= goal); //decrease the number of remaining tokens remainingTokens = remainingTokens.sub(tokens); // mint tokens and transfer funds to investor token.mint(buyer, tokens); forwardFunds(); TokenPurchase(msg.sender, buyer, weiAmount, tokens); return true; } function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } function finalize() onlyOwner public { require(state == State.Running); require(ended()); uint centsWeiRaised = weiRaised.mul(ETH_USD_EXCHANGE_CENTS); uint minGoal = USD_SOFT_CAP * (10**18) * (10**2); // Check the soft goal reaching if(centsWeiRaised >= minGoal) { //token Raised uint tokenRaised = totalTokens - remainingTokens; //bitlumes tokes 25% equivelent to (tokenraied / 2) (token raised = 50 %) uint bitlumensTokens = tokenRaised.div(2); uint bountyTokens = 4 * bitlumensTokens.div(100); uint TeamTokens = bitlumensTokens.sub(bountyTokens); token.mint(bitlumensAccount, bitlumensTokens); token.mint(teamAccount, TeamTokens); token.mint(bountyAccount, bountyTokens); teamTokensDelivered = true; bountyDelivered = true; bitlumensDelivered = true; // if goal reached // stop the minting token.finishMinting(); // enable token transfers token.enableTokenTransfers(); // close the vault and transfer funds to wallet vault.close(); // ICO successfully finalized // set state to Success state = State.Success; FinalizedOK(); } else { // if goal NOT reached // ICO not successfully finalized finalizeNOK(); } } function finalizeNOK() onlyOwner public { // run checks again because this is a public function require(state == State.Running); require(ended()); // enable the refunds vault.enableRefunds(); // ICO not successfully finalised // set state to Failure state = State.Failure; FinalizedNOK(); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(state == State.Failure); vault.refund(msg.sender); } // from ICOEngineInterface function started() public view returns(bool) { return now >= startTime; } // from ICOEngineInterface function ended() public view returns(bool) { return now >= endTime || remainingTokens == 0; } function startTime() public view returns(uint) { return(startTime); } function endTime() public view returns(uint){ return(endTime); } function totalTokens() public view returns(uint){ return(totalTokens); } function remainingTokens() public view returns(uint){ return(remainingTokens); } // return the price as number of tokens released for each ether function price() public view returns(uint){ // determine which discount to apply if (now < roundTwoTime) { return(TOKEN_FIRST_PRICE_RATE); } else if (now < roundThreeTime){ return (TOKEN_SECOND_PRICE_RATE); } else if (now < roundFourTime) { return (TOKEN_THIRD_PRICE_RATE); }else if (now < roundFiveTime) { return (TOKEN_FOURTH_PRICE_RATE); } else { return (TOKEN_FIFTH_PRICE_RATE); } } // No payable fallback function, the tokens must be buyed using the functions buyTokens and buyTokensFor function () public { revert(); } }
run checks again because this is a public function enable the refunds ICO not successfully finalised set state to Failure
function finalizeNOK() onlyOwner public { require(state == State.Running); require(ended()); vault.enableRefunds(); state = State.Failure; FinalizedNOK(); }
7,285,333
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import { ERC721FairDistribution } from './ERC721FairDistribution.sol'; /** * @title CCCT * @notice The Chunky Cow Club Tour ERC721 NFT contract. */ contract CCCT is ERC721FairDistribution { constructor( uint256 maxSupply, uint256 mintPrice, uint256 maxPurchaseSize, uint256 presaleStart, uint256 presaleEnd ) ERC721FairDistribution( 'Chunky Cow Club Tour', 'CCCT', maxSupply, mintPrice, maxPurchaseSize, presaleStart, presaleEnd ) { // Mint founder cows. for (uint256 i = 0; i < 10; i++) { _safeMint(0x799e5b7fde4b8be33c7E7fCb2fc82ed1331bE024, i); } for (uint256 i = 10; i < 20; i++) { _safeMint(0x59bF8061367Dfba43A6359848c581214E0DfeF16, i); } for (uint256 i = 20; i < 30; i++) { _safeMint(0xdEf4Ed6e5Aa0Aea70503C91F12587a06dDc1e60F, i); } for (uint256 i = 30; i < 40; i++) { _safeMint(0x22f06A62F6D48c9f883d8fd1a6D5345893b6288a, i); } // Mint community/partnership cows. for (uint256 i = 40; i < 50; i++) { _safeMint(0xdC222325B0fBE26FF047A2aa373851CaDcC9DEBd, i); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import { Ownable } from '@openzeppelin/contracts/access/Ownable.sol'; import { ERC721 } from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import { ERC721Enumerable } from '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import { SafeMath } from '@openzeppelin/contracts/utils/math/SafeMath.sol'; /** * @title ERC721FairDistribution * @author this-is-obvs * * @notice ERC721 base contract supporting a fair and random distribution of tokens, with a fixed * minting price. The owner of the contract is responsible for ensuring that the NFT works are * stored in decentralized storage, and provably linked to this contract via _provenanceHash. * * The following events should happen in order, coordinated by the contract owner: * 1. The pre-sale begins, during which tokens may be purchased, but the NFT pieces have not yet * been revealed. * 2. The _provenanceHash is finalized on-chain, acting as a commitment to the content and * metadata of the NFT series, as well as the order of original sequence IDs. * 3. A starting index is chosen pseudorandomly and is used to determine how the NFT token IDs * are mapped to original sequence IDs. This helps to ensure a fair distribution. * 4. The NFT pieces are revealed, by updating the _baseTokenUri. * 5. After the conclusion of the sale, it is recommended that the contract owner renounce * ownership, to prevent further changes to the _baseTokenUri or _provenanceHash. Before * giving up ownership, the owner may call pauseMinting(), if necessary, to cap the supply. * * The starting index is determined pseudorandomly using a recent block hash once one of the * following occurs: * 1. The last token is purchased; OR * 2. The first token is purchased after the _presaleEnd timestamp; OR * 3. If either of the above takes too long to occur, the owner may take manual action to ensure * that the starting index is chosen promptly. * * Once the starting index is chosen, each NFT token ID is mapped to an original sequence ID * according to the formula: * * Original Sequence ID = (NFT Token ID + Starting Index) % Max Supply */ contract ERC721FairDistribution is ERC721Enumerable, Ownable { using SafeMath for uint256; event Withdrew(uint256 balance); event MintPriceUpdated(uint256 mintPrice); event PresaleStartUpdated(uint256 presaleStart); event PresaleEndUpdated(uint256 presaleEnd); event BaseTokenUriUpdated(string baseTokenUri); event ProvenanceHashUpdated(string provenanceHash); event MintingPaused(); event MintingUnpaused(); event SetStartingIndexBlockNumber(uint256 blockNumber, bool usedForce); event SetStartingIndex(uint256 startingIndex, uint256 blockNumber); /// @notice The maximum number of tokens which may ever be minted. uint256 public immutable MAX_SUPPLY; /// @notice Max tokens which can be purchased per call to the mint() function. uint256 public immutable MAX_PURCHASE_QUANTITY; /// @notice The price to mint a token. uint256 public _mintPrice; /// @notice The timestamp marking the start of the pre-sale. uint256 public _presaleStart; /// @notice The timestamp marking the end of the pre-sale. uint256 public _presaleEnd; /// @notice The block number to be used to derive the starting index. uint256 public _startingIndexBlockNumber; /// @notice The starting index, chosen pseudorandomly to help ensure a fair distribution. uint256 public _startingIndex; /// @notice The base URI used to retrieve the data associated with the tokens. string internal _baseTokenUri; /// @notice A hash provided by the contract owner to commit to the content, metadata, and /// sequence order of the NFT series. string public _provenanceHash; /// @notice Indicates whether minting has been paused by the contract owner. bool public _isMintingPaused; constructor( string memory name, string memory symbol, uint256 maxSupply, uint256 mintPrice, uint256 maxPurchaseSize, uint256 presaleStart, uint256 presaleEnd ) ERC721(name, symbol) { MAX_SUPPLY = maxSupply; MAX_PURCHASE_QUANTITY = maxPurchaseSize; _mintPrice = mintPrice; _presaleStart = presaleStart; _presaleEnd = presaleEnd; emit PresaleStartUpdated(presaleStart); emit PresaleEndUpdated(presaleEnd); } function mintPresale() external onlyOwner { // Mint cows sold during the pre-sale, to be distributed separately. for (uint256 i = 50; i < 119; i++) { _safeMint(0xdEf4Ed6e5Aa0Aea70503C91F12587a06dDc1e60F, i); } require(totalSupply() == 119); } /** * @notice Withdraw contract funds. * * @return The withdrawn amount. */ function withdraw() external onlyOwner returns (uint256) { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); emit Withdrew(balance); return balance; } /** * @notice Set the mint price (denominated in wei). */ function setMintPrice(uint256 mintPrice) external onlyOwner { _mintPrice = mintPrice; emit MintPriceUpdated(mintPrice); } /** * @notice Set the timestamp which marks the start of the pre-sale. */ function setPresaleStart(uint256 presaleStart) external onlyOwner { _presaleStart = presaleStart; emit PresaleStartUpdated(presaleStart); } /** * @notice Set the timestamp which marks the end of the pre-sale. */ function setPresaleEnd(uint256 presaleEnd) external onlyOwner { _presaleEnd = presaleEnd; emit PresaleEndUpdated(presaleEnd); } /** * @notice Set the base URI. This is used to update the NFT off-chain content and/or metadata. * This should be called at the conclusion of the pre-sale, after the starting index has been * selected, in order to reveal the final NFT pieces. */ function setBaseTokenUri(string memory baseUri) external onlyOwner { _baseTokenUri = baseUri; emit BaseTokenUriUpdated(baseUri); } /** * @notice Set the hash committing to the content, metadata, and sequence order of the NFT series. */ function setProvenanceHash(string memory provenanceHash) external onlyOwner { _provenanceHash = provenanceHash; emit ProvenanceHashUpdated(provenanceHash); } /** * @notice Pause minting. */ function pauseMinting() external onlyOwner { _isMintingPaused = true; emit MintingPaused(); } /** * @notice Unpause minting. */ function unpauseMinting() external onlyOwner { _isMintingPaused = false; emit MintingUnpaused(); } /** * @notice Mint a token. */ function mint(uint256 purchaseQuantity) external payable { require(block.timestamp >= _presaleStart, 'The sale has not started'); require(!_isMintingPaused, 'Minting is disabled'); require(purchaseQuantity <= MAX_PURCHASE_QUANTITY, 'Max purchase quantity exceeded'); require(totalSupply().add(purchaseQuantity) <= MAX_SUPPLY, 'Purchase would exceed max supply'); require(_mintPrice.mul(purchaseQuantity) <= msg.value, 'Insufficient payment received'); for(uint256 i = 0; i < purchaseQuantity; i++) { _safeMint(msg.sender, totalSupply()); } if (_startingIndexBlockNumber != 0) { return; } // Finalize the starting index as soon as either of the following occurs: // 1. The first token is purchased after the _presaleEnd timestamp; OR // 2. The final token is purchased. if ( block.timestamp > _presaleEnd || totalSupply() == MAX_SUPPLY ) { _startingIndexBlockNumber = block.number; emit SetStartingIndexBlockNumber(block.number, false); } } /** * @notice Fix the starting index for the collection using the previously determined block number. */ function setStartingIndex() external { uint256 targetBlock = _startingIndexBlockNumber; require(targetBlock != 0, 'Starting index block number has not been set'); // If the hash for the desired block is unavailable, fall back to the most recent block. if (block.number.sub(targetBlock) > 256) { targetBlock = block.number - 1; } uint256 startingIndex = uint256(blockhash(targetBlock)) % MAX_SUPPLY; emit SetStartingIndex(startingIndex, targetBlock); _startingIndex = startingIndex; } /** * @notice Set the starting index block number, which will determine the starting index for the * collection. This is still pseudorandom since the starting index will depend on the hash of * the current block. * * An appropriate time to call this would be after some window of time following the _presaleEnd * timestamp, if time passes without anyone purchasing a token. In such a situation, it is in * the community's interests for the owner to finalize the starting index, to reduce the * opportunity for anyone to manipulate the starting index. For best security/fairness, the * length of the window of time to wait should be committed to by the contract owner before the * time indicated by the _presaleEnd timestamp. */ function forceSetStartingIndexBlock() external onlyOwner { require(_startingIndexBlockNumber == 0, 'Starting index block number is already set'); _startingIndexBlockNumber = block.number; emit SetStartingIndexBlockNumber(block.number, true); } function _baseURI() internal view override returns (string memory) { return _baseTokenUri; } } // 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 () { 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.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}. 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
Set the starting index block number, which will determine the starting index for the collection. This is still pseudorandom since the starting index will depend on the hash of the current block. An appropriate time to call this would be after some window of time following the _presaleEnd timestamp, if time passes without anyone purchasing a token. In such a situation, it is in the community's interests for the owner to finalize the starting index, to reduce the opportunity for anyone to manipulate the starting index. For best security/fairness, the length of the window of time to wait should be committed to by the contract owner before the time indicated by the _presaleEnd timestamp./
function forceSetStartingIndexBlock() external onlyOwner { require(_startingIndexBlockNumber == 0, 'Starting index block number is already set'); _startingIndexBlockNumber = block.number; emit SetStartingIndexBlockNumber(block.number, true); }
477,038
//SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IRefunder.sol"; import "./IRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title Refunder - core contract for refunding arbitrary contract+indentifier calls * between 96%-99% of the gas costs of the transaction */ contract Refunder is ReentrancyGuard, Ownable, Pausable, IRefunder { using Address for address; /// @notice Address of the refunder registry address public registry; /// @notice The maximum allowed gas price that the refunder is willing to refund uint256 public maxGasPrice = 0; /** * @notice The base gas cost of the `relayAndRefun` transaction up until the point where the first `gasLeft` is executed * Important: Gas costs for the transaction arguments are not included! * Calculation: base 21_000 + 128 (8 non_zero_identifier_bytes) + 96 (24 zero_identifier_bytes) + 762 (gas costs until gasProvided variable) */ uint256 public constant BASE_TX_COST = 21986; /// @notice The gas cost for executing refund internal function + emitting RelayAndRefund event uint256 public constant REFUND_OP_COST = 6440; /** * @notice Struct storing the refundable data for a given target * isSupported marks whether the refundable is supported or not * validatingContract contract address to call for business logic validation on every refund * validatingIdentifier identifier to call for business logic validation on every refund */ struct Refundable { bool isSupported; address validatingContract; bytes4 validatingIdentifier; } /// @notice refundables mapping storing all of the supported `target` + `identifier` refundables mapping(address => mapping(bytes4 => Refundable)) public refundables; /// @notice Deposit event emitted once someone deposits ETH to the contract event Deposit(address indexed depositor, uint256 amount); /// @notice Withdraw event emitted once the owner withdraws ETH from the contract event Withdraw(address indexed recipient, uint256 amount); /// @notice GasPriceChange event emitted once the Max Gas Price is updated event GasPriceChange(uint256 newGasPrice); /// @notice RefundableUpdate event emitted once the owner updates the refundables event RefundableUpdate( address indexed targetContract, bytes4 indexed identifier, bool isRefundable, address validatingContract, bytes4 validatingIdentifier ); /// @notice RelayAndRefund event emitted once someone executes transaction for which the contract will refund him of up to 99% of the cost event RelayAndRefund( address indexed caller, address indexed target, bytes4 indexed identifier, uint256 refundAmount ); /** * @notice Constructor * @param _registry The address of the registry */ constructor(address _registry) { registry = _registry; } /** * @notice Validates that the provided target+identifier is marked as refundable and that the gas price is * lower than the maximum allowed one * @param targetContract the contract that will be called * @param identifier the function to be called */ modifier onlySupportedParams(address targetContract, bytes4 identifier) { require(tx.gasprice <= maxGasPrice, "Refunder: Invalid gas price"); require( refundables[targetContract][identifier].isSupported, "Refunder: Non-refundable call" ); _; } /** * @notice calculates the net gas cost for refunding and refunds the msg.sender afterwards */ modifier netGasCost(address target, bytes4 identifier) { uint256 gasProvided = gasleft(); _; uint256 gasUsedSoFar = gasProvided - gasleft(); uint256 gas = gasUsedSoFar + BASE_TX_COST + REFUND_OP_COST; uint256 refundAmount = gas * tx.gasprice; Address.sendValue(msg.sender, refundAmount); emit RelayAndRefund(msg.sender, target, identifier, refundAmount); } /// @notice receive function for depositing ETH into the contract receive() external payable { emit Deposit(msg.sender, msg.value); } /** * @notice Withdraws ETH from the contract * @param amount amount of ETH to withdraw */ function withdraw(uint256 amount) external override onlyOwner nonReentrant { require( address(this).balance >= amount, "Refunder: Insufficient balance" ); Address.sendValue(msg.sender, amount); emit Withdraw(msg.sender, amount); } /** * @notice Updates the maximum gas price of transactions that the refunder will refund * @param gasPrice the maximum gas price to refund */ function setMaxGasPrice(uint256 gasPrice) external override onlyOwner { maxGasPrice = gasPrice; emit GasPriceChange(gasPrice); } /** * @notice Updates the map of the refundables. Refundable can be added / removed depending on the isRefundable param * @param targetContract the contract for which we are updating the refundables * @param identifier the function for which we are updating the refundables * @param isRefundable_ whether the contract will refund the combination of `target` + `iterfaceId` or not */ function updateRefundable( address targetContract, bytes4 identifier, bool isRefundable_, address validatingContract, bytes4 validatingIdentifier ) external override onlyOwner { refundables[targetContract][identifier] = Refundable( isRefundable_, validatingContract, validatingIdentifier ); IRegistry(registry).updateRefundable( targetContract, identifier, isRefundable_ ); emit RefundableUpdate( targetContract, identifier, isRefundable_, validatingContract, validatingIdentifier ); } /** * @notice Benchmarks the gas costs and executes `target` + `identifier` with the provided `arguments` * Once executed, the msg.sender gets refunded up to 99% of the gas cost * @param target the contract to call * @param identifier the function to call * @param arguments the bytes of data to pass as arguments */ function relayAndRefund( address target, bytes4 identifier, bytes memory arguments ) external override netGasCost(target, identifier) nonReentrant onlySupportedParams(target, identifier) whenNotPaused returns (bytes memory) { Refundable memory _refundableData = refundables[target][identifier]; if (_refundableData.validatingContract != address(0)) { bytes memory validationArgs = abi.encodeWithSelector( _refundableData.validatingIdentifier, msg.sender, target, identifier, arguments ); (bool success, bytes memory returnData) = _refundableData.validatingContract.call(validationArgs); require(success, "Refunder: Validating contract reverted"); bool isAllowed = abi.decode(returnData, (bool)); require( isAllowed, "Refunder: Validating contract rejected the refund" ); } bytes memory data = abi.encodeWithSelector(identifier, arguments); (bool success, bytes memory returnData) = target.call(data); require(success, "Refunder: Function call not successful"); return returnData; } /// @notice Pauses refund operations of the contract function pause() external override onlyOwner { _pause(); } /// @notice Unpauses the refund operations of the contract function unpause() external override onlyOwner { _unpause(); } /// @notice Returns true/false whether the function getRefundable(address target, bytes4 identifier) external view returns (Refundable memory) { return refundables[target][identifier]; } }
Returns true/false whether the
function getRefundable(address target, bytes4 identifier) external view returns (Refundable memory) { return refundables[target][identifier]; }
12,883,181
// SPDX-License-Identifier: UNLICENSED // This code is the property of the Aardbanq DAO. // The Aardbanq DAO is located at 0x829c094f5034099E91AB1d553828F8A765a3DaA1 on the Ethereum Main Net. // It is the author's wish that this code should be open sourced under the MIT license, but the final // decision on this would be taken by the Aardbanq DAO with a vote once sufficient ABQ tokens have been // distributed. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity >=0.7.0; import "./SafeMathTyped.sol"; import "./Erc20.sol"; import './Minter.sol'; import "./IPricer.sol"; import "./ILiquidityEstablisher.sol"; /// @notice Allow buying of tokens in batches of increasing price. contract ScaleBuying is IPricer { /// @notice The token to use for purchasing Erc20 public paymentAsset; /// @notice The token that is being bought Erc20 public boughtAsset; /// @notice The minter for the token being bought Minter public minter; /// @notice The date in unix timestamp (seconds) when the sale closes. uint64 public closingDate; /// @notice The address to which the funds should be sent to. address public treasury; /// @notice The location of the ILO, used to know when tokens can be claimed. ILiquidityEstablisher public liquidityEstablisher; /// @notice The amount that has been awarded so far. uint256 public amountAwarded; /// @notice The initial price for the sale. uint256 public initialPrice; /// @notice The price increase for each token block. uint256 public priceIncrease; /// @notice The amount of tokens per block. uint256 public tokensPerPriceBlock; /// @notice The number of blocks up for sale. uint256 public maxBlocks; /// @notice The amounts of tokens claimable by an address. mapping(address => uint256) public amountsClaimable; /// @notice Constructs a ScaleBuying /// @param _paymentAsset The token address to be used for payment. /// @param _boughtAsset The token address to be issued. /// @param _minter The minter for the issued token. /// @param _treasury The address to receive all funds. /// @param _initialPrice The initial price per token. /// @param _priceIncrease The increase of the price per token for each block. /// @param _tokensPerPriceBlock The tokens in each block. /// @param _maxBlocks The maximum number of blocks on sale. /// @param _closingDate The date in unix (seconds) timestamp that the sale will close. constructor (Erc20 _paymentAsset, Erc20 _boughtAsset, Minter _minter, address _treasury, uint256 _initialPrice, uint256 _priceIncrease, uint256 _tokensPerPriceBlock, uint256 _maxBlocks, uint64 _closingDate) { paymentAsset = _paymentAsset; boughtAsset = _boughtAsset; minter = _minter; treasury = _treasury; amountAwarded = 0; initialPrice = _initialPrice; priceIncrease = _priceIncrease; tokensPerPriceBlock = _tokensPerPriceBlock; maxBlocks = _maxBlocks; closingDate = _closingDate; allocateTokensRaisedByAuction(); } // CG: This allocates the amount of tokens that was already bought on auction before\ // switching over to this Scale Buying. function allocateTokensRaisedByAuction() private { uint256 price = initialPrice; uint256 buyerAAmount = 7165 ether; amountsClaimable[0xEE779e4b3e7b11454ed80cFE12Cf48ee3Ff4579E] = buyerAAmount; emit Bought(0xEE779e4b3e7b11454ed80cFE12Cf48ee3Ff4579E, buyerAAmount, price); uint256 buyerBAmount = 4065 ether; amountsClaimable[0x6C4f3Db0E743A9e8f44A756b6585192B358D7664] = buyerBAmount; emit Bought(0x6C4f3Db0E743A9e8f44A756b6585192B358D7664, buyerAAmount, price); uint256 buyerCAmount = 355 ether; amountsClaimable[0x0FB79E6C0F5447ffe36a0050221275Da487b0E09] = buyerCAmount; emit Bought(0x0FB79E6C0F5447ffe36a0050221275Da487b0E09, buyerAAmount, price); amountAwarded = buyerAAmount + buyerBAmount + buyerCAmount; } /// @notice Set the ILO to use to track if liquidity has been astablished and thus claims can be allowed. /// @param _liquidityEstablisher The ILO. function setLiquidityEstablisher(ILiquidityEstablisher _liquidityEstablisher) external { require(address(liquidityEstablisher) == address(0), "ABQDAO/already-set"); liquidityEstablisher = _liquidityEstablisher; } /// @notice The event emitted when a claim is executed. /// @param claimer The address the claim has been processed for. /// @param amount The amount that was claimed. event Claimed(address indexed claimer, uint256 amount); /// @notice Claim ABQ bought for the given address. Claims can only be processed after liquidity has been established. /// @param _target The address to process claims for. function claim(address _target) external { // CG: Claims cannot be executed before liquidity is established or closed more than a week ago. require(liquidityEstablisher.isLiquidityEstablishedOrExpired(), "ABQDAO/cannot-claim-yet"); uint256 amountClaimable = amountsClaimable[_target]; if (amountClaimable > 0) { bool isSuccess = boughtAsset.transfer(_target, amountClaimable); require(isSuccess, "ABQDAO/could-not-transfer-claim"); amountsClaimable[_target] = 0; emit Claimed(_target, amountClaimable); } } /// @notice The event emitted when tokens are bought. /// @param buyer The address that may claim the tokens. /// @param amount The amount of token bought. /// @param pricePerToken The price per token that the tokens were bought for. event Bought(address indexed buyer, uint256 amount, uint256 pricePerToken); /// @notice Buy tokens in the current block. /// @param _paymentAmount The amount to spend. This will be transfered from msg.sender who should approved this amount first. /// @param _target The address that the amounts would be bought for. Tokens are distributed after calling the claim method. function buy(uint256 _paymentAmount, address _target) external returns (uint256 _paymentLeft) { // CG: only allow buys before the ico closes. require(block.timestamp <= closingDate, "ABQDAO/ico-concluded"); (uint256 paymentLeft, uint256 paymentDue) = buyInBlock(_paymentAmount, _target); // CG: transfer payment if (paymentDue > 0) { bool isSuccess = paymentAsset.transferFrom(msg.sender, treasury, paymentDue); require(isSuccess, "ABQDAO/could-not-pay"); } return paymentLeft; } function buyInBlock(uint256 _paymentAmount, address _target) private returns (uint256 _paymentLeft, uint256 _paymentDue) { uint256 currentBlockIndex = currentBlock(); uint256 tokensLeft = tokensLeftInBlock(currentBlockIndex); if (currentBlockIndex >= maxBlocks) { // CG: If all block are sold out, then amount bought should be zero. return (_paymentAmount, 0); } else { uint256 currentPriceLocal = currentPrice(); uint256 tokensCanPayFor = _paymentAmount / currentPriceLocal; if (tokensCanPayFor == 0) { return (_paymentAmount, 0); } if (tokensCanPayFor > (tokensLeft / 1 ether)) { tokensCanPayFor = tokensLeft / 1 ether; } // CG: Get the amount of tokens that can be bought in this block. uint256 paymentDue = SafeMathTyped.mul256(tokensCanPayFor, currentPriceLocal); tokensCanPayFor = SafeMathTyped.mul256(tokensCanPayFor, 1 ether); amountsClaimable[_target] = SafeMathTyped.add256(amountsClaimable[_target], tokensCanPayFor); amountAwarded = SafeMathTyped.add256(amountAwarded, tokensCanPayFor); minter.mint(address(this), tokensCanPayFor); emit Bought(_target, tokensCanPayFor, currentPriceLocal); uint256 paymentLeft = SafeMathTyped.sub256(_paymentAmount, paymentDue); if (paymentLeft <= currentPriceLocal) { return (paymentLeft, paymentDue); } else { // CG: should this block be sold out, buy the remainder in the next box. (uint256 subcallPaymentLeft, uint256 subcallPaymentDue) = buyInBlock(paymentLeft, _target); paymentDue = SafeMathTyped.add256(paymentDue, subcallPaymentDue); return (subcallPaymentLeft, paymentDue); } } } /// @notice Get the current price per token. /// @return _currentPrice The current price per token. function currentPrice() view public override returns (uint256 _currentPrice) { return SafeMathTyped.add256(initialPrice, SafeMathTyped.mul256(currentBlock(), priceIncrease)); } /// @notice Get the current block number, starting at 0. function currentBlock() view public returns (uint256 _currentBlock) { return amountAwarded / tokensPerPriceBlock; } /// @notice Get the amount of tokens left in a given block. /// @param _block The block to get the number of tokens left for. /// @return _tokensLeft The number of tokens left in the given _block. function tokensLeftInBlock(uint256 _block) view public returns (uint256 _tokensLeft) { uint256 currentBlockIndex = currentBlock(); if (_block > maxBlocks || _block < currentBlockIndex) { return 0; } if (_block == currentBlockIndex) { //CG: non overflow code: return ((currentBlockIndex + 1) * tokensPerPriceBlock) - amountAwarded; return SafeMathTyped.sub256(SafeMathTyped.mul256(SafeMathTyped.add256(currentBlockIndex, 1), tokensPerPriceBlock), amountAwarded); } else { return tokensPerPriceBlock; } } }
Buy tokens in the current block. _paymentAmount The amount to spend. This will be transfered from msg.sender who should approved this amount first. _target The address that the amounts would be bought for. Tokens are distributed after calling the claim method. CG: only allow buys before the ico closes. CG: transfer payment
function buy(uint256 _paymentAmount, address _target) external returns (uint256 _paymentLeft) { require(block.timestamp <= closingDate, "ABQDAO/ico-concluded"); (uint256 paymentLeft, uint256 paymentDue) = buyInBlock(_paymentAmount, _target); if (paymentDue > 0) { bool isSuccess = paymentAsset.transferFrom(msg.sender, treasury, paymentDue); require(isSuccess, "ABQDAO/could-not-pay"); } return paymentLeft; }
6,103,303
./full_match/2222/0xD510b3A5bdC8292E5a4efA0836654f335Ac3AB19/sources/contracts/liquidity-commitment-contracts/contracts/GMI.sol
Internal function to burn GMI tokens from the specified account This function performs the following actions: - Retrieves the balance information of the specified account from the userBalances mapping - Requires that the GMI balance of the account is greater than 0 - Calculates the WAGMI amount based on the locked WAGMI and GMI shares of the account - Requires that the WAGMI amount is greater than 0 - Calls the _withdrawPlatformShares() function to withdraw platform shares - Calls the _claim() function to claim rewards for the account's GMI shares - Updates the total supply, locked WAGMI, locked WAGMI in the balance, and GMI shares in an unchecked manner - Calls the _updateUserDebt() function to update the user's debt - Starts vesting the WAGMI amount for the specified account using the wagmiVesting contract account The address of the account to burn GMI tokens from amount The amount of GMI tokens to burn/
function _burn(address account, uint256 amount) private { UserInfo storage balance = userBalances[account]; require(balance.gmiShares >= amount, "insufficient GMI balance"); require(block.number - balance.lastMint > MINIMUM_LOCK_PERIOD_IN_BLOCKS, "too early"); uint256 wagmiAmount = (balance.wagmiLocked * amount) / balance.gmiShares; require(wagmiAmount > 0, "the amount is too small"); unchecked { total.supply -= amount; total.lockedWagmi -= wagmiAmount; balance.wagmiLocked -= wagmiAmount; balance.gmiShares -= amount; } Order storage order = orders[msg.sender]; if (order.gmiAmount > balance.gmiShares && order.deadline > block.timestamp) { order.gmiAmount = balance.gmiShares; } wagmiVesting.startVesting(account, wagmiAmount); }
7,102,514
// contracts/Box.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.8.4; pragma solidity ^0.6.6; // Import Ownable from the OpenZeppelin Contracts library import "@openzeppelin/contracts/access/Ownable.sol"; // Import Auth from the access-control subdirectory import "./Auth.sol"; contract Box is Ownable { /// Using these values to manipulate the random value on each die roll. /// The goal is an attempt to further randomize randomness for each die rolled. /** * 77194726158210796949047323339125271902179989777093709359638389338608753093290 * 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * 10101010101010101010101010101... */ // uint constant MODIFIER_VALUE_1 = 77194726158210796949047323339125271902179989777093709359638389338608753093290; /** * 38597363079105398474523661669562635951089994888546854679819194669304376546645 * 0x55555555555555555555555555555555555555555555555555555555555555555 * 0101010101... */ // uint constant MODIFIER_VALUE_2 = 38597363079105398474523661669562635951089994888546854679819194669304376546645; uint constant MAX_DICE_ALLOWED = 10; uint constant MAX_DIE_SIZE_ALLOWED = 100; int constant MAX_ADJUSTMENT_ALLOWED = 20; // int8 private constant ROLL_IN_PROGRESS = 42; // bytes32 private chainLinkKeyHash; // uint256 private chainlinkVRFFee; struct DiceRollee { address rollee; uint256 timestamp; /// When the die were rolled uint256 randomness; /// Stored to help verify/debug results uint128 numberOfDie; /// 1 = roll once, 4 = roll four die uint128 dieSize; // 6 = 6 sided die, 20 = 20 sided die int128 adjustment; /// Can be a positive or negative value int128 result; /// Result of all die rolls and adjustment. Can be negative because of a negative adjustment. /// Max value can be 1000 (10 * 100 sided die rolled) uint256 hasRolled; /// Used in some logic tests uint128[] rolledValues; /// array of individual rolls. These can only be positive. } /** * Mapping between the requestID (returned when a request is made), * and the address of the roller. This is so the contract can keep track of * who to assign the result to when it comes back. */ // mapping(bytes32 => address) private rollers; /// Used to indicate if an address has ever rolled. mapping(address => bool) private rollers; /// stores the roller and the state of their current die roll. /// This is useful so we can see if the dice have actually landed yet. mapping(address => DiceRollee) private currentRoll; /// users can have multiple die rolls mapping (address => DiceRollee[]) rollerHistory; /// keep list of user addresses for fun/stats /// can iterate over them later. address[] internal rollerAddresses; /// Emit this when either of the rollDice functions are called. /// Used to notify soem front end that we are waiting for response from /// chainlink VRF. // event DiceRolled(bytes32 indexed requestId, address indexed roller); /// Emitted when fulfillRandomness is called by Chainlink VRF to provide the random value. // event DiceLanded( // bytes32 indexed requestId, // address indexed roller, // uint8[] rolledvalues, // int8 adjustment, // int16 result // ); modifier validateNumberOfDie(uint _numberOfDie) { require(_numberOfDie <= MAX_DICE_ALLOWED, "Too many dice!"); _; } modifier validateDieSize(uint _dieSize) { require(_dieSize <= MAX_DIE_SIZE_ALLOWED, "100 sided die is the max allowed."); _; } modifier validateAdjustment(int128 _adjustment) { int128 tempAdjustment = _adjustment >= 0 ? _adjustment : -_adjustment; // convert to positive value and test that. require(tempAdjustment <= MAX_ADJUSTMENT_ALLOWED, "Adjustment is too large."); _; } uint256 private _value; Auth private _auth; event ValueChanged(uint256 value); constructor() public { _auth = new Auth(msg.sender); } // The onlyOwner modifier restricts who can call the store function function store(uint256 value) public onlyOwner{ // Require that the caller is registered as an administrator in Auth require(_auth.isAdministrator(msg.sender), "Unauthorized"); _value = value; emit ValueChanged(value); } function retrieve() public view returns (uint256) { return _value; } /// Used to perform specific logic based on if user has rolled previoulsy or not. function hasRolledOnce(address _member) public view returns(bool) { // return (rollerHistory[_member].length > 0); return (getUserRollsCount(_member) > 0); } /// Used to perform specific logic based on if user has rolled previoulsy or not. function hasRolledBefore(address _member) public view returns(bool) { return (rollers[_member]); } /// How many times someone rolled. function getUserRollsCount(address _address) public view returns (uint) { return rollerHistory[_address].length; } /** * Called by the front end if user wants to use the front end to * generate the random values. We just use this to store the result of the roll on the blockchain. * * @param _numberOfDie how many dice are rolled * @param _dieSize the type of die rolled (4 = 4 sided, 6 = six sided, etc.) * @param _adjustment the modifier to add after all die have been rolled. Can be negative. * @param _result can be negative if you have a low enough dice roll and larger negative adjustment. * Example, rolled 2 4 sided die with -4 adjustment. */ function hasRolled(uint128 _numberOfDie, uint128 _dieSize, int128 _adjustment, int128 _result) public validateNumberOfDie(_numberOfDie) validateDieSize(_dieSize) validateAdjustment(_adjustment) { // DiceRollee memory diceRollee = DiceRollee( // msg.sender, // block.timestamp, // 0, // _numberOfDie, // _dieSize, // _adjustment, // _result, // true, // new uint8[](_numberOfDie) // ); DiceRollee memory diceRollee = DiceRollee({ rollee: msg.sender, timestamp: block.timestamp, randomness: 0, numberOfDie: _numberOfDie, dieSize: _dieSize, adjustment: _adjustment, result: _result, hasRolled: 1, rolledValues: new uint128[](_numberOfDie) }); // no need to store the current roll, because there is none. currentRoll[msg.sender] = diceRollee; rollerHistory[msg.sender].push(diceRollee); /// Only add roller to this list once. // if (! hasRolledOnce(msg.sender)) { if (! hasRolledBefore(msg.sender)) { rollers[msg.sender] = true; rollerAddresses.push(msg.sender); } } }
The onlyOwner modifier restricts who can call the store function Require that the caller is registered as an administrator in Auth
function store(uint256 value) public onlyOwner{ require(_auth.isAdministrator(msg.sender), "Unauthorized"); _value = value; emit ValueChanged(value); }
13,088,697
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Upgradeable.sol"; import "./RewardableBridge.sol"; import "./BasicHomeBridge.sol"; import "./BaseOverdrawManagement.sol"; /** * @title HomeOverdrawManagement * @dev This contract implements functionality for recovering from out-of-limits executions in Home side vanilla bridges. */ contract HomeOverdrawManagement is BaseOverdrawManagement, RewardableBridge, Upgradeable, BasicHomeBridge { using SafeMath for uint256; /** * @dev Fixes locked tokens, that were out of execution limits during the call to executeAffirmation. * @param hashMsg reference for bridge operation that was out of execution limits. * @param unlockOnForeign true if fixed tokens should be unlocked to the other side of the bridge. * @param valueToUnlock unlocked amount of tokens, should be less than txAboveLimitsValue. * Should be less than maxPerTx(), if tokens need to be unlocked on the other side. */ function fixAssetsAboveLimits(bytes32 hashMsg, bool unlockOnForeign, uint256 valueToUnlock) external onlyIfUpgradeabilityOwner { uint256 signed = numAffirmationsSigned(hashMsg); require(!isAlreadyProcessed(signed)); (address recipient, uint256 value) = txAboveLimits(hashMsg); require(recipient != address(0) && value > 0 && value >= valueToUnlock); setOutOfLimitAmount(outOfLimitAmount().sub(valueToUnlock)); uint256 pendingValue = value.sub(valueToUnlock); setTxAboveLimitsValue(pendingValue, hashMsg); emit AssetAboveLimitsFixed(hashMsg, valueToUnlock, pendingValue); if (unlockOnForeign) { require(valueToUnlock <= maxPerTx()); address feeManager = feeManagerContract(); uint256 eventValue = valueToUnlock; if (feeManager != address(0)) { uint256 fee = calculateFee(valueToUnlock, false, feeManager, HOME_FEE); eventValue = valueToUnlock.sub(fee); } emit UserRequestForSignature(recipient, eventValue); } } /** * @dev Internal function for clearing above limits markers for some failed transfer. * Useful when transfer is being reprocessed on a new day or after limits were updated. * It is required that fixAssetsAboveLimits was not called on the failed transfer before prior to this function. * @param _hashMsg hash of the message, works as a unique indentifier. * @param _value transferred amount of tokens/coins in the fixed message. */ function _clearAboveLimitsMarker(bytes32 _hashMsg, uint256 _value) internal { (address aboveLimitsRecipient, uint256 aboveLimitsValue) = txAboveLimits(_hashMsg); // check if transfer was marked as out of limits if (aboveLimitsRecipient != address(0)) { // revert if a given transaction hash was already processed by the call to fixAssetsAboveLimits require(aboveLimitsValue == _value); setTxAboveLimits(address(0), 0, _hashMsg); setOutOfLimitAmount(outOfLimitAmount().sub(_value)); } } }
Internal function for clearing above limits markers for some failed transfer. Useful when transfer is being reprocessed on a new day or after limits were updated. It is required that fixAssetsAboveLimits was not called on the failed transfer before prior to this function. _hashMsg hash of the message, works as a unique indentifier. _value transferred amount of tokens/coins in the fixed message./ check if transfer was marked as out of limits revert if a given transaction hash was already processed by the call to fixAssetsAboveLimits
function _clearAboveLimitsMarker(bytes32 _hashMsg, uint256 _value) internal { (address aboveLimitsRecipient, uint256 aboveLimitsValue) = txAboveLimits(_hashMsg); if (aboveLimitsRecipient != address(0)) { require(aboveLimitsValue == _value); setTxAboveLimits(address(0), 0, _hashMsg); setOutOfLimitAmount(outOfLimitAmount().sub(_value)); } }
1,779,330
pragma solidity >=0.4.22 <0.9.0; pragma experimental ABIEncoderV2; //import {IterableMapping} from "./IterableMapping.sol"; //import {AccessControl} from "../node_modules/openzeppelin-solidity/contracts/access/AccessControl.sol"; //import './IterableMapping.sol'; //import {User} from './User.sol'; contract PersonalInfo{ // using IterableMapping for IterableMapping.Map; // IterableMapping.Map private map; struct PersonalStruct{ address userAddress; string contact; //时间 string postcode; //时间 string gender; //时间 uint age; //时间 uint[4] basicSet; //症状 uint index; bool isValid; } uint[] indexSet; //临时存储用 string[] stringSet; //临时存储用 PersonalStruct[] private personalSet; // address[] addrSet; mapping(address =>PersonalStruct) addressToStruct; mapping(uint =>PersonalStruct) indexToStruct; event StorageF(uint t0); event ShowList(uint[] uintSet, string[] strSet); function addPersonal(address _ad,string memory _contact,uint _age,string memory _gender,uint[4] memory _bSet, string memory _pcode)public { PersonalStruct memory hs; uint index= personalSet.length; hs= PersonalStruct(_ad,_contact,_pcode,_gender,_age,_bSet,index,true); personalSet.push(hs); //uint t0= hs.symSet[0]; addressToStruct[_ad]=hs; indexToStruct[index]=hs; //emit StorageF(t0); } // function findBasic(address _ad) public view returns(uint){ uint[4] memory tset=addressToStruct[_ad].basicSet; uint t0 = tset[0]; return t0; } function findById(uint id) public view returns(string memory,uint[4] memory,string memory){ PersonalStruct memory hs=indexToStruct[id]; return (hs.contact,hs.basicSet,hs.gender); } function showList(address _ad)public{ uint len=indexSet.length; if(len >0){ delete indexSet; delete stringSet; } for(uint i=0;i<personalSet.length;i++){ if(personalSet[i].userAddress==_ad ){ indexSet.push(i); // stringSet.push(personalSet[i].startTime); } } emit ShowList(indexSet,stringSet); } }
stringSet.push(personalSet[i].startTime);
function showList(address _ad)public{ uint len=indexSet.length; if(len >0){ delete indexSet; delete stringSet; } for(uint i=0;i<personalSet.length;i++){ if(personalSet[i].userAddress==_ad ){ indexSet.push(i); } } emit ShowList(indexSet,stringSet); }
5,405,924
pragma solidity >=0.4.22 <0.6.0; contract HealthCare { address private hospitalAdmin; address private labAdmin; struct Record { uint256 ID; uint256 price; uint256 signatureCount; string testName; string date; string hospitalName; bool isValue; address pAddr; mapping (address => uint256) signatures; } modifier signOnly { require (msg.sender == hospitalAdmin || msg.sender == labAdmin ); _; } constructor() public { hospitalAdmin = msg.sender; labAdmin = 0xF6F2F51c07e44efE7BC25E0EC6B332f39d930ac0; //assigning a hard coded address from ganache } // Mapping to store records mapping (uint256=> Record) public _records; uint256[] public recordsArr; event recordCreated(uint256 ID, string testName, string date, string hospitalName, uint256 price); event recordSigned(uint256 ID, string testName, string date, string hospitalName, uint256 price); // Create new record function newRecord (uint256 _ID, string memory _tName, string memory _date, string memory hName, uint256 price) public{ Record storage _newrecord = _records[_ID]; // Only allows new records to be created require(!_records[_ID].isValue); _newrecord.pAddr = msg.sender; _newrecord.ID = _ID; _newrecord.testName = _tName; _newrecord.date = _date; _newrecord.hospitalName = hName; _newrecord.price = price; _newrecord.isValue = true; _newrecord.signatureCount = 0; recordsArr.push(_ID); emit recordCreated(_newrecord.ID, _tName, _date, hName, price); } // Function to sign a record function signRecord(uint256 _ID) signOnly public { Record storage records = _records[_ID]; // Checks the aunthenticity of the address signing it require(address(0) != records.pAddr); require(msg.sender != records.pAddr); // Doesn't allow the same person to sign twice require(records.signatures[msg.sender] != 1); records.signatures[msg.sender] = 1; records.signatureCount++; // Checks if the record has been signed by both the authorities to process insurance claim if(records.signatureCount == 2) emit recordSigned(records.ID, records.testName, records.date, records.hospitalName, records.price); } }
Create new record Only allows new records to be created
function newRecord (uint256 _ID, string memory _tName, string memory _date, string memory hName, uint256 price) public{ Record storage _newrecord = _records[_ID]; require(!_records[_ID].isValue); _newrecord.pAddr = msg.sender; _newrecord.ID = _ID; _newrecord.testName = _tName; _newrecord.date = _date; _newrecord.hospitalName = hName; _newrecord.price = price; _newrecord.isValue = true; _newrecord.signatureCount = 0; recordsArr.push(_ID); emit recordCreated(_newrecord.ID, _tName, _date, hName, price); }
7,299,388
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../interfaces/IPermittedNFTs.sol"; import "../interfaces/INftTypeRegistry.sol"; import "../interfaces/INftfiHub.sol"; import "../utils/Ownable.sol"; import "../utils/ContractKeys.sol"; /** * @title PermittedNFTsAndTypeRegistry * @author NFTfi * @dev Registry for NFT contracts supported by NFTfi. * Each NFT is associated with an NFT Type. */ contract PermittedNFTsAndTypeRegistry is Ownable, IPermittedNFTs { INftfiHub public hub; mapping(bytes32 => address) private nftTypes; /** * @notice A mapping from an NFT contract's address to the Token type of that contract. A zero Token Type indicates * non-permitted. */ mapping(address => bytes32) private nftPermits; /* ****** */ /* EVENTS */ /* ****** */ /** * @notice This event is fired whenever the admins register a ntf type. * * @param nftType - Nft type represented by keccak256('nft type'). * @param nftWrapper - Address of the wrapper contract. */ event TypeUpdated(bytes32 indexed nftType, address indexed nftWrapper); /** * @notice This event is fired whenever the admin sets a NFT's permit. * * @param nftContract - Address of the NFT contract. * @param nftType - NTF type e.g. bytes32("CRYPTO_KITTIES") */ event NFTPermit(address indexed nftContract, bytes32 indexed nftType); /* ********* */ /* MODIFIERS */ /* ********* */ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwnerOrAirdropFactory(string memory _nftType) { if ( ContractKeys.getIdFromStringKey(_nftType) == ContractKeys.getIdFromStringKey(ContractKeys.AIRDROP_WRAPPER_STRING) ) { require(hub.getContract(ContractKeys.AIRDROP_FACTORY) == _msgSender(), "caller is not AirdropFactory"); } else { require(owner() == _msgSender(), "caller is not owner"); } _; } /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `nftTypeRegistry` * Initialize `nftPermits` with a batch of permitted NFTs * * @param _admin - Initial admin of this contract. * @param _nftfiHub - Address of the NftfiHub contract * @param _definedNftTypes - All the ossible nft types * @param _definedNftWrappers - All the possible wrappers for the types * @param _permittedNftContracts - The addresses of the NFT contracts. * @param _permittedNftTypes - The NFT Types. e.g. "CRYPTO_KITTIES" * - "" means "disable this permit" * - != "" means "enable permit with the given NFT Type" */ constructor( address _admin, address _nftfiHub, string[] memory _definedNftTypes, address[] memory _definedNftWrappers, address[] memory _permittedNftContracts, string[] memory _permittedNftTypes ) Ownable(_admin) { hub = INftfiHub(_nftfiHub); _setNftTypes(_definedNftTypes, _definedNftWrappers); _setNFTPermits(_permittedNftContracts, _permittedNftTypes); } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @notice This function can be called by admins to change the permitted list status of an NFT contract. This * includes both adding an NFT contract to the permitted list and removing it. * `_nftContract` can not be zero address. * * @param _nftContract - The address of the NFT contract. * @param _nftType - The NFT Type. e.g. "CRYPTO_KITTIES" * - "" means "disable this permit" * - != "" means "enable permit with the given NFT Type" */ function setNFTPermit(address _nftContract, string memory _nftType) external override onlyOwnerOrAirdropFactory(_nftType) { _setNFTPermit(_nftContract, _nftType); } /** * @notice This function can be called by admins to change the permitted list status of a batch NFT contracts. This * includes both adding an NFT contract to the permitted list and removing it. * `_nftContract` can not be zero address. * * @param _nftContracts - The addresses of the NFT contracts. * @param _nftTypes - The NFT Types. e.g. "CRYPTO_KITTIES" * - "" means "disable this permit" * - != "" means "enable permit with the given NFT Type" */ function setNFTPermits(address[] memory _nftContracts, string[] memory _nftTypes) external onlyOwner { _setNFTPermits(_nftContracts, _nftTypes); } /** * @notice This function can be called by anyone to lookup the Nft Type associated with the contract. * @param _nftContract - The address of the NFT contract. * @notice Returns the NFT Type: * - bytes32("") means "not permitted" * - != bytes32("") means "permitted with the given NFT Type" */ function getNFTPermit(address _nftContract) external view override returns (bytes32) { return nftPermits[_nftContract]; } /** * @notice This function can be called by anyone to lookup the address of the NftWrapper associated to the * `_nftContract` type. * @param _nftContract - The address of the NFT contract. */ function getNFTWrapper(address _nftContract) external view override returns (address) { bytes32 nftType = nftPermits[_nftContract]; return getNftTypeWrapper(nftType); } /** * @notice Set or update the wrapper contract address for the given NFT Type. * Set address(0) for a nft type for un-register such type. * * @param _nftType - The nft type, e.g. "ERC721", or "ERC1155". * @param _nftWrapper - The address of the wrapper contract that implements INftWrapper behaviour for dealing with * NFTs. */ function setNftType(string memory _nftType, address _nftWrapper) external onlyOwner { _setNftType(_nftType, _nftWrapper); } /** * @notice Batch set or update the wrappers contract address for the given batch of NFT Types. * Set address(0) for a nft type for un-register such type. * * @param _nftTypes - The nft types, e.g. "ERC721", or "ERC1155". * @param _nftWrappers - The addresses of the wrapper contract that implements INftWrapper behaviour for dealing * with NFTs. */ function setNftTypes(string[] memory _nftTypes, address[] memory _nftWrappers) external onlyOwner { _setNftTypes(_nftTypes, _nftWrappers); } /** * @notice This function can be called by anyone to get the contract address that implements the given nft type. * * @param _nftType - The nft type, e.g. bytes32("ERC721"), or bytes32("ERC1155"). */ function getNftTypeWrapper(bytes32 _nftType) public view returns (address) { return nftTypes[_nftType]; } /** * @notice Set or update the wrapper contract address for the given NFT Type. * Set address(0) for a nft type for un-register such type. * * @param _nftType - The nft type, e.g. "ERC721", or "ERC1155". * @param _nftWrapper - The address of the wrapper contract that implements INftWrapper behaviour for dealing with * NFTs. */ function _setNftType(string memory _nftType, address _nftWrapper) internal { require(bytes(_nftType).length != 0, "nftType is empty"); bytes32 nftTypeKey = ContractKeys.getIdFromStringKey(_nftType); nftTypes[nftTypeKey] = _nftWrapper; emit TypeUpdated(nftTypeKey, _nftWrapper); } /** * @notice Batch set or update the wrappers contract address for the given batch of NFT Types. * Set address(0) for a nft type for un-register such type. * * @param _nftTypes - The nft types, e.g. keccak256("ERC721"), or keccak256("ERC1155"). * @param _nftWrappers - The addresses of the wrapper contract that implements INftWrapper behaviour for dealing * with NFTs. */ function _setNftTypes(string[] memory _nftTypes, address[] memory _nftWrappers) internal { require(_nftTypes.length == _nftWrappers.length, "setNftTypes function information arity mismatch"); for (uint256 i = 0; i < _nftWrappers.length; i++) { _setNftType(_nftTypes[i], _nftWrappers[i]); } } /** * @notice This function changes the permitted list status of an NFT contract. This includes both adding an NFT * contract to the permitted list and removing it. * @param _nftContract - The address of the NFT contract. * @param _nftType - The NFT Type. e.g. bytes32("CRYPTO_KITTIES") * - bytes32("") means "disable this permit" * - != bytes32("") means "enable permit with the given NFT Type" */ function _setNFTPermit(address _nftContract, string memory _nftType) internal { require(_nftContract != address(0), "nftContract is zero address"); bytes32 nftTypeKey = ContractKeys.getIdFromStringKey(_nftType); if (nftTypeKey != 0) { require(getNftTypeWrapper(nftTypeKey) != address(0), "NFT type not registered"); } require( nftPermits[_nftContract] != ContractKeys.getIdFromStringKey(ContractKeys.AIRDROP_WRAPPER_STRING), "AirdropWrapper can't be modified" ); nftPermits[_nftContract] = nftTypeKey; emit NFTPermit(_nftContract, nftTypeKey); } /** * @notice This function changes the permitted list status of a batch NFT contracts. This includes both adding an * NFT contract to the permitted list and removing it. * @param _nftContracts - The addresses of the NFT contracts. * @param _nftTypes - The NFT Types. e.g. "CRYPTO_KITTIES" * - "" means "disable this permit" * - != "" means "enable permit with the given NFT Type" */ function _setNFTPermits(address[] memory _nftContracts, string[] memory _nftTypes) internal { require(_nftContracts.length == _nftTypes.length, "setNFTPermits function information arity mismatch"); for (uint256 i = 0; i < _nftContracts.length; i++) { _setNFTPermit(_nftContracts[i], _nftTypes[i]); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedNFTs { function setNFTPermit(address _nftContract, string memory _nftType) external; function getNFTPermit(address _nftContract) external view returns (bytes32); function getNFTWrapper(address _nftContract) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftTypeRegistry * @author NFTfi * @dev Interface for NFT Types Registry supported by NFTfi. */ interface INftTypeRegistry { function setNftType(bytes32 _nftType, address _nftWrapper) external; function getNftTypeWrapper(bytes32 _nftType) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftfiHub * @author NFTfi * @dev NftfiHub interface */ interface INftfiHub { function setContract(string calldata _contractKey, address _contractAddress) external; function getContract(bytes32 _contractKey) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. * * Modified version from openzeppelin/contracts/access/Ownable.sol that allows to * initialize the owner using a parameter in the constructor */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /** * @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); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Sets the owner. */ function _setOwner(address _newOwner) private { address oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(oldOwner, _newOwner); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title ContractKeys * @author NFTfi * @dev Common library for contract keys */ library ContractKeys { bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S"); bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS"); bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS"); bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY"); bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY"); bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER"); bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S"); bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS"); bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER"); bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY"); bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN"); bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER"); string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper"; /** * @notice Returns the bytes32 representation of a string * @param _key the string key * @return id bytes32 representation */ function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) { require(bytes(_key).length <= 32, "invalid key"); // solhint-disable-next-line no-inline-assembly assembly { id := mload(add(_key, 32)) } } } // 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; } }
Batch set or update the wrappers contract address for the given batch of NFT Types. Set address(0) for a nft type for un-register such type. _nftTypes - The nft types, e.g. "ERC721", or "ERC1155". _nftWrappers - The addresses of the wrapper contract that implements INftWrapper behaviour for dealing with NFTs./
function setNftTypes(string[] memory _nftTypes, address[] memory _nftWrappers) external onlyOwner { _setNftTypes(_nftTypes, _nftWrappers); }
179,145
/* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IVault } from "../interfaces/IVault.sol"; import { CommonMath } from "../../lib/CommonMath.sol"; /** * @title CoreIssuanceLibrary * @author Set Protocol * * This library contains functions for calculating deposit, withdrawal,and transfer quantities */ library CoreIssuanceLibrary { using SafeMath for uint256; /** * Calculate the quantities required to deposit and decrement during issuance. Takes into account * the tokens an owner already has in the vault. * * @param _components Addresses of components * @param _componentQuantities Component quantities to increment and withdraw * @param _owner Address to deposit and decrement quantities from * @param _vault Address to vault * @return uint256[] decrementQuantities Quantities to decrement from vault * @return uint256[] depositQuantities Quantities to deposit into the vault */ function calculateDepositAndDecrementQuantities( address[] calldata _components, uint256[] calldata _componentQuantities, address _owner, address _vault ) external view returns ( uint256[] memory /* decrementQuantities */, uint256[] memory /* depositQuantities */ ) { uint256 componentCount = _components.length; uint256[] memory decrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory depositQuantities = new uint256[](componentCount); for (uint256 i = 0; i < componentCount; i++) { // Fetch component quantity in vault uint256 vaultBalance = IVault(_vault).getOwnerBalance( _components[i], _owner ); // If the vault holds enough components, decrement the full amount if (vaultBalance >= _componentQuantities[i]) { decrementTokenOwnerValues[i] = _componentQuantities[i]; } else { // User has less than required amount, decrement the vault by full balance if (vaultBalance > 0) { decrementTokenOwnerValues[i] = vaultBalance; } depositQuantities[i] = _componentQuantities[i].sub(vaultBalance); } } return ( decrementTokenOwnerValues, depositQuantities ); } /** * Calculate the quantities required to withdraw and increment during redeem and withdraw. Takes into * account a bitmask exclusion parameter. * * @param _componentQuantities Component quantities to increment and withdraw * @param _toExclude Mask of indexes of tokens to exclude from withdrawing * @return uint256[] incrementQuantities Quantities to increment in vault * @return uint256[] withdrawQuantities Quantities to withdraw from vault */ function calculateWithdrawAndIncrementQuantities( uint256[] calldata _componentQuantities, uint256 _toExclude ) external pure returns ( uint256[] memory /* incrementQuantities */, uint256[] memory /* withdrawQuantities */ ) { uint256 componentCount = _componentQuantities.length; uint256[] memory incrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory withdrawToValues = new uint256[](componentCount); // Loop through and decrement vault balances for the set, withdrawing if requested for (uint256 i = 0; i < componentCount; i++) { // Calculate bit index of current component uint256 componentBitIndex = CommonMath.safePower(2, i); // Transfer to user unless component index is included in _toExclude if ((_toExclude & componentBitIndex) != 0) { incrementTokenOwnerValues[i] = _componentQuantities[i]; } else { withdrawToValues[i] = _componentQuantities[i]; } } return ( incrementTokenOwnerValues, withdrawToValues ); } /** * Calculate the required component quantities required for issuance or rdemption for a given * quantity of Set Tokens * * @param _componentUnits The units of the component token * @param _naturalUnit The natural unit of the Set token * @param _quantity The number of tokens being redeem * @return uint256[] Required quantities in base units of components */ function calculateRequiredComponentQuantities( uint256[] calldata _componentUnits, uint256 _naturalUnit, uint256 _quantity ) external pure returns (uint256[] memory) { require( _quantity.mod(_naturalUnit) == 0, "CoreIssuanceLibrary: Quantity must be a multiple of nat unit" ); uint256[] memory tokenValues = new uint256[](_componentUnits.length); // Transfer the underlying tokens to the corresponding token balances for (uint256 i = 0; i < _componentUnits.length; i++) { tokenValues[i] = _quantity.div(_naturalUnit).mul(_componentUnits[i]); } return tokenValues; } }
Calculate the quantities required to withdraw and increment during redeem and withdraw. Takes into account a bitmask exclusion parameter. _componentQuantities Component quantities to increment and withdraw _toExclude Mask of indexes of tokens to exclude from withdrawing return uint256[] incrementQuantities Quantities to increment in vault return uint256[] withdrawQuantities Quantities to withdraw from vault/ Loop through and decrement vault balances for the set, withdrawing if requested Calculate bit index of current component Transfer to user unless component index is included in _toExclude
function calculateWithdrawAndIncrementQuantities( uint256[] calldata _componentQuantities, uint256 _toExclude ) external pure returns ( uint256[] memory /* incrementQuantities */, uint256[] memory /* withdrawQuantities */ ) { uint256 componentCount = _componentQuantities.length; uint256[] memory incrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory withdrawToValues = new uint256[](componentCount); for (uint256 i = 0; i < componentCount; i++) { uint256 componentBitIndex = CommonMath.safePower(2, i); if ((_toExclude & componentBitIndex) != 0) { incrementTokenOwnerValues[i] = _componentQuantities[i]; withdrawToValues[i] = _componentQuantities[i]; } } return ( incrementTokenOwnerValues, withdrawToValues ); }
12,948,225
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract Staking is Ownable, ReentrancyGuard { constructor(address _token) { token = ERC20(_token); } ERC20 public token; uint public rewardsPool = 0; //частное и знаменатель в множителе награды uint private rewardsMultiplier = 1; uint private rewardsDivisor = 1000; //частное и знаменатель в множителе бонуса uint private bonusMultiplier = 1; uint private bonusDivisor = 1000; bool public isContractLocked = false; struct Balance { uint amount; uint time; uint withdrawnRewards; uint writeOffedBonus; } mapping (address => Balance) private balances; modifier notZero(uint _amount) { require(_amount != 0, "Can't transfer zero tokens"); _; } modifier lockable() { require(!isContractLocked, "Contract is locked for transactoins"); _; } event Deposit(address user, uint amount); event Withdraw(address user, uint amount); event WriteOffBonus(address user, uint amount); event WithdrawRewards(address user, uint amount); /** * @dev deposit tokens for stake them. If the user had rewards, they are transfered on his address. * @param _amount amount of tokens */ function deposit(uint _amount) external notZero(_amount) lockable nonReentrant { _resetRewardsAndBonus(); _deposit(_amount); balances[msg.sender].time = block.timestamp; balances[msg.sender].amount += _amount; } /** * @dev withdraw tokens from stake. If the user had rewards, they are transfered on his address. * @param _amount amount of tokens */ function withdraw(uint _amount) external lockable nonReentrant notZero(_amount) { _withdrawBalance(_amount); } /** * @dev withdraw all tokens from stake. If the user had rewards, they are transfered on his address. */ function withdrawAll() external lockable nonReentrant{ _withdrawBalance(balances[msg.sender].amount); } /** * @dev get stake balance of user */ function getBalance(address _user) external view returns(uint) { return balances[_user].amount; } /** * @dev get bonus of user */ function getBonus(address _user) public view returns(uint) { Balance memory currentBalance = balances[_user]; uint elapsedTime = block.timestamp - currentBalance.time; return currentBalance.amount * elapsedTime * bonusMultiplier / bonusDivisor - currentBalance.writeOffedBonus; } /** * @dev get rewards of user */ function getRewards(address _user) public view returns(uint){ Balance memory currentBalance = balances[_user]; uint elapsedTime = block.timestamp - currentBalance.time; return currentBalance.amount * elapsedTime * rewardsMultiplier / rewardsDivisor - currentBalance.withdrawnRewards; } /** * @dev write off bonus of msg.sender * @param _amount amount of bonuses */ function writeOffBonus(uint _amount) external nonReentrant notZero(_amount){ _writeOffBonus(_amount); } /** * @dev write off all bonus of msg.sender */ function writeOffBonusFull() external nonReentrant { _writeOffBonus(getBonus(msg.sender)); } /** * @dev withdraw rewards of msg.sender * @param _amount amount of rewards */ function withdrawRewards(uint _amount) external nonReentrant notZero(_amount){ _withdrawRewards(_amount); } /** * @dev withdraw all rewards of msg.sender */ function withdrawAllRewards() external nonReentrant{ _withdrawRewards(getRewards(msg.sender)); } function _writeOffBonus(uint _amount) private { require(getBonus(msg.sender) >= _amount, "Insufficient bonus"); balances[msg.sender].writeOffedBonus += _amount; emit WriteOffBonus(msg.sender, _amount); } function _withdrawRewards(uint _amount) private { require(getRewards(msg.sender) >= _amount, "Insufficient rewards"); require(rewardsPool >= _amount , "Insufficient rewards pool"); _withdraw(_amount); balances[msg.sender].withdrawnRewards += _amount; rewardsPool -= _amount; emit WithdrawRewards(msg.sender, _amount); } function _resetRewardsAndBonus() private { uint bonus = getBonus(msg.sender); uint rewards = getRewards(msg.sender); if (bonus != 0) { _writeOffBonus(bonus); balances[msg.sender].writeOffedBonus = 0; } if (rewards != 0) { _withdrawRewards(rewards); balances[msg.sender].withdrawnRewards = 0; } } function _withdrawBalance(uint _amount) private { require(balances[msg.sender].amount >= _amount, "Insufficient balance"); _resetRewardsAndBonus(); _withdraw(_amount); balances[msg.sender].time = block.timestamp; balances[msg.sender].amount -= _amount; } function _withdraw(uint _amount) private { require(token.balanceOf(address(this)) >= _amount, "Insufficient tokens on the contract"); require(token.transfer(msg.sender, _amount), "Failed to withdraw tokens"); emit Withdraw(msg.sender, _amount); } function _deposit(uint _amount) private { uint currentAllowance = token.allowance(msg.sender, address(this)); require(currentAllowance >= _amount, "Insufficient allowance"); require(token.transferFrom(msg.sender, address(this), _amount), "Failed to deposit tokens"); emit Deposit(msg.sender, _amount); } //FOR OWNER-------------------------------------------------- /** * @dev lock contract for deposit and withdraw */ function lockContract() external onlyOwner{ require(!isContractLocked, "Contract is locked"); isContractLocked = true; } /** * @dev unlock contract for deposit and withdraw */ function unlockContract() external onlyOwner{ require(isContractLocked, "Contract is unlocked"); isContractLocked = false; } /** * @dev set address of staked token */ function setToken(address _token) external onlyOwner { token = ERC20(_token); } /** * @dev change factor for rewards */ function setRewardsFactor(uint _multiplier, uint _divisor) external onlyOwner { rewardsMultiplier = _multiplier; rewardsDivisor = _divisor; } /** * @dev change factor for bonus */ function setBonusFactor(uint _multiplier, uint _divisor) external onlyOwner { bonusMultiplier = _multiplier; bonusDivisor = _divisor; } /** * @dev add rewards to pool */ function addRewardsToPool(uint _amount) external onlyOwner { rewardsPool += _amount; _deposit(_amount); } /** * @dev withdraw rewards from pool */ function withdrawRewardsFromPool(uint _amount) external onlyOwner { require(rewardsPool >= _amount, "Insufficient rewards pool"); _withdraw(_amount); } }
deposit tokens for stake them. If the user had rewards, they are transfered on his address. _amount amount of tokens/
function deposit(uint _amount) external notZero(_amount) lockable nonReentrant { _resetRewardsAndBonus(); _deposit(_amount); balances[msg.sender].time = block.timestamp; balances[msg.sender].amount += _amount; }
12,890,088
// contracts/multisender.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.7; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } pragma solidity 0.5.7; /** * @title UpgradeabilityStorage * @dev This contract holds all the necessary state variables to support the upgrade functionality */ contract UpgradeabilityStorage { // Version name of the current implementation string internal _version; // Address of the current implementation address internal _implementation; /** * @dev Tells the version name of the current implementation * @return string representing the name of the current version */ function version() public view returns (string memory) { return _version; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } } pragma solidity 0.5.7; /** * @title UpgradeabilityOwnerStorage * @dev This contract keeps track of the upgradeability owner */ contract UpgradeabilityOwnerStorage { // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } } pragma solidity 0.5.7; /** * @title OwnedUpgradeabilityStorage * @dev This is the storage necessary to perform upgradeable contracts. * This means, required state variables for upgradeability purpose and eternal storage per se. */ contract OwnedUpgradeabilityStorage is UpgradeabilityOwnerStorage, UpgradeabilityStorage, EternalStorage {} pragma solidity 0.5.7; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner(), "not an owner"); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[keccak256("owner")]; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner the address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); setOwner(newOwner); } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { emit OwnershipTransferred(owner(), newOwner); addressStorage[keccak256("owner")] = newOwner; } } pragma solidity 0.5.7; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is EternalStorage, Ownable { function pendingOwner() public view returns (address) { return addressStorage[keccak256("pendingOwner")]; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner()); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); addressStorage[keccak256("pendingOwner")] = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner(), pendingOwner()); addressStorage[keccak256("owner")] = addressStorage[keccak256("pendingOwner")]; addressStorage[keccak256("pendingOwner")] = address(0); } } pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity 0.5.7; contract Messages is EternalStorage { struct Authorization { address authorizedSigner; uint256 expiration; } /** * Domain separator encoding per EIP 712. * keccak256( * "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" * ) */ bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472; /** * Validator struct type encoding per EIP 712 * keccak256( * "Authorization(address authorizedSigner,uint256 expiration)" * ) */ bytes32 private constant AUTHORIZATION_TYPEHASH = 0xe419504a688f0e6ea59c2708f49b2bbc10a2da71770bd6e1b324e39c73e7dc25; /** * Domain separator per EIP 712 */ // bytes32 public DOMAIN_SEPARATOR; function DOMAIN_SEPARATOR() public view returns(bytes32) { bytes32 salt = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a558; return keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Multisender"), keccak256("2.0"), uintStorage[keccak256("chainId")], address(this), salt )); } /** * @notice Calculates authorizationHash according to EIP 712. * @param _authorizedSigner address of trustee * @param _expiration expiration date * @return bytes32 EIP 712 hash of _authorization. */ function hash(address _authorizedSigner, uint256 _expiration) public pure returns (bytes32) { return keccak256(abi.encode( AUTHORIZATION_TYPEHASH, _authorizedSigner, _expiration )); } /** * @return the recovered address from the signature */ function recoverAddress( bytes32 messageHash, bytes memory signature ) public view returns (address) { bytes32 r; bytes32 s; bytes1 v; // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), messageHash )); return ecrecover(digest, uint8(v), r, s); } function getApprover(uint256 timestamp, bytes memory signature) public view returns(address) { if (timestamp < now) { return address(0); } bytes32 messageHash = hash(msg.sender, timestamp); return recoverAddress(messageHash, signature); } } pragma solidity 0.5.7; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract UpgradebleStormSender is OwnedUpgradeabilityStorage, Claimable, Messages { using SafeMath for uint256; event Multisended(uint256 total, address tokenAddress); event ClaimedTokens(address token, address owner, uint256 balance); event PurchaseVIP(address customer, uint256 tier); modifier hasFee() { uint256 contractFee = currentFee(msg.sender); if (contractFee > 0) { require(msg.value >= contractFee, "no fee"); } _; } modifier validLists(uint256 _contributorsLength, uint256 _balancesLength) { require(_contributorsLength > 0, "no contributors sent"); require( _contributorsLength == _balancesLength, "different arrays lengths" ); _; } function() external payable {} function initialize( address _owner, uint256 _fee, uint256 _vipPrice0, uint256 _vipPrice1, uint256 _vipPrice2, uint256 _chainId ) public { require(!initialized() || msg.sender == owner()); setOwner(_owner); setFee(_fee); // 0.05 ether fee setVipPrice(0, _vipPrice0); // 1 eth setVipPrice(1, _vipPrice1); // 5 eth setVipPrice(2, _vipPrice2); // 10 eth uintStorage[keccak256("chainId")] = _chainId; boolStorage[keccak256("rs_multisender_initialized")] = true; require(fee() >= 0.01 ether); uintStorage[keccak256("referralFee")] = 0.01 ether; } function initialized() public view returns (bool) { return boolStorage[keccak256("rs_multisender_initialized")]; } function fee() public view returns (uint256) { return uintStorage[keccak256("fee")]; } function currentFee(address _customer) public view returns (uint256) { if (getUnlimAccess(_customer) >= block.timestamp) { return 0; } return fee(); } function setFee(uint256 _newStep) public onlyOwner { require(_newStep != 0); uintStorage[keccak256("fee")] = _newStep; } function tokenFallback(address _from, uint256 _value, bytes memory _data) public {} function _checkFee(address _user, address payable _referral) internal { uint256 contractFee = currentFee(_user); if (contractFee > 0) { require(msg.value >= contractFee, "no fee"); if (_referral != address(0)) { _referral.send(referralFee()); } } } function multisendToken( address _token, address[] calldata _contributors, uint256[] calldata _balances, uint256 _total, address payable _referral ) external payable validLists(_contributors.length, _balances.length) { bool isGoodToken; bytes memory data; _checkFee(msg.sender, _referral); uint256 change = 0; ERC20 erc20token = ERC20(_token); // bytes4 transferFrom = 0x23b872dd; (isGoodToken, data) = _token.call( abi.encodeWithSelector( 0x23b872dd, msg.sender, address(this), _total ) ); require(isGoodToken, "transferFrom failed"); if (data.length > 0) { bool success = abi.decode(data, (bool)); require(success, "not enough allowed tokens"); } for (uint256 i = 0; i < _contributors.length; i++) { (bool success, ) = _token.call( abi.encodeWithSelector( erc20token.transfer.selector, _contributors[i], _balances[i] ) ); if (!success) { change += _balances[i]; } } if (change != 0) { erc20token.transfer(msg.sender, change); } emit Multisended(_total, _token); } function findBadAddressesForBurners( address _token, address[] calldata _contributors, uint256[] calldata _balances, uint256 _total ) external payable validLists(_contributors.length, _balances.length) hasFee returns (address[] memory badAddresses, uint256[] memory badBalances) { badAddresses = new address[](_contributors.length); badBalances = new uint256[](_contributors.length); ERC20 erc20token = ERC20(_token); for (uint256 i = 0; i < _contributors.length; i++) { (bool success, ) = _token.call( abi.encodeWithSelector( erc20token.transferFrom.selector, msg.sender, _contributors[i], _balances[i] ) ); if (!success) { badAddresses[i] = _contributors[i]; badBalances[i] = _balances[i]; } } } function multisendTokenForBurners( address _token, address[] calldata _contributors, uint256[] calldata _balances, uint256 _total, address payable _referral ) external payable validLists(_contributors.length, _balances.length) { _checkFee(msg.sender, _referral); ERC20 erc20token = ERC20(_token); for (uint256 i = 0; i < _contributors.length; i++) { (bool success, ) = _token.call( abi.encodeWithSelector( erc20token.transferFrom.selector, msg.sender, _contributors[i], _balances[i] ) ); } emit Multisended(_total, _token); } function multisendTokenForBurnersWithSignature( address _token, address[] calldata _contributors, uint256[] calldata _balances, uint256 _total, address payable _referral, bytes calldata _signature, uint256 _timestamp ) external payable { address tokenHolder = getApprover(_timestamp, _signature); require( tokenHolder != address(0), "the signature is invalid or has expired" ); require(_contributors.length > 0, "no contributors sent"); require( _contributors.length == _balances.length, "different arrays lengths" ); // require(msg.value >= currentFee(tokenHolder), "no fee"); _checkFee(tokenHolder, _referral); ERC20 erc20token = ERC20(_token); for (uint256 i = 0; i < _contributors.length; i++) { (bool success, ) = _token.call( abi.encodeWithSelector( erc20token.transferFrom.selector, tokenHolder, _contributors[i], _balances[i] ) ); } emit Multisended(_total, _token); } function multisendTokenWithSignature( address _token, address[] calldata _contributors, uint256[] calldata _balances, uint256 _total, address payable _referral, bytes calldata _signature, uint256 _timestamp ) external payable { bool isGoodToken; address tokenHolder = getApprover(_timestamp, _signature); require( tokenHolder != address(0), "the signature is invalid or has expired" ); require(_contributors.length > 0, "no contributors sent"); require( _contributors.length == _balances.length, "different arrays lengths" ); _checkFee(tokenHolder, _referral); uint256 change = 0; (isGoodToken, ) = _token.call( abi.encodeWithSelector( 0x23b872dd, tokenHolder, address(this), _total ) ); require(isGoodToken, "not enough allowed tokens"); for (uint256 i = 0; i < _contributors.length; i++) { (bool success, ) = _token.call( abi.encodeWithSelector( // transfer 0xa9059cbb, _contributors[i], _balances[i] ) ); if (!success) { change += _balances[i]; } } if (change != 0) { _token.call( abi.encodeWithSelector( // transfer 0xa9059cbb, tokenHolder, change ) ); } emit Multisended(_total, _token); } // DONT USE THIS METHOD, only for eth_call function tokenFindBadAddresses( address _token, address[] calldata _contributors, uint256[] calldata _balances, uint256 _total ) external payable validLists(_contributors.length, _balances.length) hasFee returns (address[] memory badAddresses, uint256[] memory badBalances) { badAddresses = new address[](_contributors.length); badBalances = new uint256[](_contributors.length); ERC20 erc20token = ERC20(_token); bool isGoodToken; (isGoodToken, ) = _token.call( abi.encodeWithSelector( 0x23b872dd, msg.sender, address(this), _total ) ); // erc20token.transferFrom(msg.sender, address(this), _total); for (uint256 i = 0; i < _contributors.length; i++) { (bool success, ) = _token.call( abi.encodeWithSelector( erc20token.transfer.selector, _contributors[i], _balances[i] ) ); if (!success) { badAddresses[i] = _contributors[i]; badBalances[i] = _balances[i]; } } } // DONT USE THIS METHOD, only for eth_call function etherFindBadAddresses( address payable[] calldata _contributors, uint256[] calldata _balances ) external payable validLists(_contributors.length, _balances.length) returns (address[] memory badAddresses, uint256[] memory badBalances) { badAddresses = new address[](_contributors.length); badBalances = new uint256[](_contributors.length); uint256 _total = msg.value; uint256 _contractFee = currentFee(msg.sender); _total = _total.sub(_contractFee); for (uint256 i = 0; i < _contributors.length; i++) { bool _success = _contributors[i].send(_balances[i]); if (!_success) { badAddresses[i] = _contributors[i]; badBalances[i] = _balances[i]; } else { _total = _total.sub(_balances[i]); } } } function multisendEther( address payable[] calldata _contributors, uint256[] calldata _balances ) external payable validLists(_contributors.length, _balances.length) { uint256 _contractBalanceBefore = address(this).balance.sub(msg.value); uint256 _total = msg.value; uint256 _contractFee = currentFee(msg.sender); _total = _total.sub(_contractFee); for (uint256 i = 0; i < _contributors.length; i++) { bool _success = _contributors[i].send(_balances[i]); if (_success) { _total = _total.sub(_balances[i]); } } uint256 _contractBalanceAfter = address(this).balance; // assert. Just for sure require( _contractBalanceAfter >= _contractBalanceBefore.add(_contractFee), "don’t try to take the contract money" ); emit Multisended(_total, 0x000000000000000000000000000000000000bEEF); } function setVipPrice(uint256 _tier, uint256 _price) public onlyOwner { uintStorage[keccak256(abi.encodePacked("vip", _tier))] = _price; } function setAddressToVip(address _address, uint256 _tier) external onlyOwner { setUnlimAccess(_address, _tier); emit PurchaseVIP(msg.sender, _tier); } function buyVip(uint256 _tier) external payable { require( msg.value >= uintStorage[keccak256(abi.encodePacked("vip", _tier))] ); setUnlimAccess(msg.sender, _tier); emit PurchaseVIP(msg.sender, _tier); } function setReferralFee(uint256 _newFee) external onlyOwner { require(fee() >= _newFee); uintStorage[keccak256("referralFee")] = _newFee; } function referralFee() public view returns (uint256) { return uintStorage[keccak256("referralFee")]; } function getVipPrice(uint256 _tier) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("vip", _tier))]; } function getAllVipPrices() external view returns (uint256 tier0, uint256 tier1, uint256 tier2) { return ( uintStorage[keccak256(abi.encodePacked("vip", uint256(0)))], uintStorage[keccak256(abi.encodePacked("vip", uint256(1)))], uintStorage[keccak256(abi.encodePacked("vip", uint256(2)))] ); } function claimTokens(address _token, uint256 _amount) external onlyOwner { address payable ownerPayable = address(uint160(owner())); uint256 amount = _amount; if (_amount == 0) { amount = address(this).balance; } if (_token == address(0)) { ownerPayable.transfer(amount); return; } ERC20 erc20token = ERC20(_token); amount = erc20token.balanceOf(address(this)); erc20token.transfer(ownerPayable, amount); emit ClaimedTokens(_token, ownerPayable, amount); } function getDeadline(uint256 _tier) public view returns (uint256) { // 1 day if (_tier == 0) { return block.timestamp + 1 days; } // 7 days if (_tier == 1) { return block.timestamp + 7 days; } // Lifetime if (_tier == 2) { return block.timestamp + 30 days; } return 0; } function getUnlimAccess(address customer) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("unlimAccess", customer))]; } function setUnlimAccess(address customer, uint256 _tier) private { uintStorage[keccak256( abi.encodePacked("unlimAccess", customer) )] = getDeadline(_tier); } function exploreETHBalances(address[] calldata targets) external view returns (uint256[] memory balances) { balances = new uint256[](targets.length); for (uint256 i = 0; i < targets.length; i++) { balances[i] = targets[i].balance; } } function exploreERC20Balances(ERC20 token, address[] calldata targets) external view returns (uint256[] memory balances) { balances = new uint256[](targets.length); for (uint256 i = 0; i < targets.length; i++) { balances[i] = token.balanceOf(targets[i]); } } }
Domain separator per EIP 712/ bytes32 public DOMAIN_SEPARATOR;
function DOMAIN_SEPARATOR() public view returns(bytes32) { bytes32 salt = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a558; return keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Multisender"), keccak256("2.0"), uintStorage[keccak256("chainId")], address(this), salt )); }
13,633,986
./full_match/1/0xDf69471Dca7c45FdC9ed0dc2E15f2232e58B9D6A/sources/browser/KASSIAHOTELRebaser.sol
rate The current exchange rate, an 18 decimal fixed point number. return If the rate is within the deviation threshold from the target rate, returns true. Otherwise, returns false./
function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); }
3,160,860
//Address: 0xa00d0080a745e6592ecdbe064ef1f698f37e1534 //Contract name: CryptoAssetCrowdsale //Balance: 0 Ether //Verification Date: 6/8/2018 //Transacion Count: 9 // CODE STARTS HERE pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract ERC20 is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is ERC20, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } /** * @title EscrowAccountCrowdsale. */ contract EscrowAccountCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; EscrowVault public vault; /** * @dev Constructor, creates EscrowAccountCrowdsale. */ function EscrowAccountCrowdsale() public { vault = new EscrowVault(wallet); } /** * @dev Investors can claim refunds here if whitelisted is unsuccessful */ function returnInvestoramount(address _beneficiary, uint256 _percentage) internal onlyOwner { vault.refund(_beneficiary,_percentage); } function afterWhtelisted(address _beneficiary) internal onlyOwner{ vault.closeAfterWhitelisted(_beneficiary); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } /** * @title EscrowVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if whitelist fails, * and forwarding it if whitelist is successful. */ contract EscrowVault is Ownable { using SafeMath for uint256; mapping (address => uint256) public deposited; address public wallet; event Closed(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function EscrowVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner payable { deposited[investor] = deposited[investor].add(msg.value); } function closeAfterWhitelisted(address _beneficiary) onlyOwner public { uint256 depositedValue = deposited[_beneficiary]; deposited[_beneficiary] = 0; wallet.transfer(depositedValue); } /** * @param investor Investor address */ function refund(address investor, uint256 _percentage)onlyOwner { uint256 depositedValue = deposited[investor]; depositedValue=depositedValue.sub(_percentage); investor.transfer(depositedValue); wallet.transfer(_percentage); emit Refunded(investor, depositedValue); deposited[investor] = 0; } } /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it whitelisted and crowdsale ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after whitelisted ends and after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } function failedWhitelist(address _beneficiary) internal { require(_beneficiary != address(0)); uint256 amount = balances[_beneficiary]; balances[_beneficiary] = 0; } function getInvestorDepositAmount(address _investor) public constant returns(uint256 paid){ return balances[_investor]; } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } contract CryptoAssetCrowdsale is TimedCrowdsale, MintedCrowdsale,EscrowAccountCrowdsale,PostDeliveryCrowdsale { enum Stage {PROCESS1_FAILED, PROCESS1_SUCCESS,PROCESS2_FAILED, PROCESS2_SUCCESS,PROCESS3_FAILED, PROCESS3_SUCCESS} //stage Phase1 or Phase2 or Phase enum Phase {PHASE1, PHASE2,PHASE3} //stage ICO Phase public phase; struct whitelisted{ Stage stage; } uint256 public adminCharge_p1=0.010 ether; uint256 public adminCharge_p2=0.13 ether; uint256 public adminCharge_p3=0.14 ether; uint256 public cap=750 ether;// softcap is 750 ether uint256 public goal=4500 ether;// hardcap is 4500 ether uint256 public minContribAmount = 0.1 ether; // min invesment mapping(address => whitelisted) public whitelist; // How much ETH each address has invested to this crowdsale mapping (address => uint256) public investedAmountOf; // How many distinct addresses have invested uint256 public investorCount; // decimalFactor uint256 public constant DECIMALFACTOR = 10**uint256(18); event updateRate(uint256 tokenRate, uint256 time); /** * @dev CryptoAssetCrowdsale is a base contract for managing a token crowdsale. * CryptoAssetCrowdsale have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ function CryptoAssetCrowdsale(uint256 _starttime, uint256 _endTime, uint256 _rate, address _wallet,ERC20 _token) TimedCrowdsale(_starttime,_endTime)Crowdsale(_rate, _wallet,_token) { phase = Phase.PHASE1; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable onlyWhileOpen{ require(_beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); uint256 volumebasedBonus=0; if(phase == Phase.PHASE1){ volumebasedBonus = tokens.mul(getTokenVolumebasedBonusRateForPhase1(tokens)).div(100); }else if(phase == Phase.PHASE2){ volumebasedBonus = tokens.mul(getTokenVolumebasedBonusRateForPhase2(tokens)).div(100); }else{ volumebasedBonus = tokens.mul(getTokenVolumebasedBonusRateForPhase3(tokens)).div(100); } tokens=tokens.add(volumebasedBonus); _preValidatePurchase( _beneficiary, weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _forwardFunds(); if(investedAmountOf[msg.sender] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[msg.sender] = investedAmountOf[msg.sender].add(weiAmount); } function tokensaleToOtherCoinUser(address beneficiary, uint256 weiAmount) public onlyOwner onlyWhileOpen { require(beneficiary != address(0) && weiAmount > 0); uint256 tokens = weiAmount.mul(rate); uint256 volumebasedBonus=0; if(phase == Phase.PHASE1){ volumebasedBonus = tokens.mul(getTokenVolumebasedBonusRateForPhase1(tokens)).div(100); }else if(phase == Phase.PHASE2){ volumebasedBonus = tokens.mul(getTokenVolumebasedBonusRateForPhase2(tokens)).div(100); }else{ volumebasedBonus = tokens.mul(getTokenVolumebasedBonusRateForPhase3(tokens)).div(100); } tokens=tokens.add(volumebasedBonus); weiRaised = weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } function validPurchase() internal constant returns (bool) { bool minContribution = minContribAmount <= msg.value; return minContribution; } function getTokenVolumebasedBonusRateForPhase1(uint256 value) internal constant returns (uint256) { uint256 bonusRate = 0; uint256 valume = value.div(DECIMALFACTOR); if (valume <= 50000 && valume >= 149999) { bonusRate = 30; } else if (valume <= 150000 && valume >= 299999) { bonusRate = 35; } else if (valume <= 300000 && valume >= 500000) { bonusRate = 40; } else{ bonusRate = 25; } return bonusRate; } function getTokenVolumebasedBonusRateForPhase2(uint256 value) internal constant returns (uint256) { uint256 bonusRate = 0; uint valume = value.div(DECIMALFACTOR); if (valume <= 50000 && valume >= 149999) { bonusRate = 25; } else if (valume <= 150000 && valume >= 299999) { bonusRate = 30; } else if (valume <= 300000 && valume >= 500000) { bonusRate = 35; } else{ bonusRate = 20; } return bonusRate; } function getTokenVolumebasedBonusRateForPhase3(uint256 value) internal constant returns (uint256) { uint256 bonusRate = 0; uint valume = value.div(DECIMALFACTOR); if (valume <= 50000 && valume >= 149999) { bonusRate = 20; } else if (valume <= 150000 && valume >= 299999) { bonusRate = 25; } else if (valume <= 300000 && valume >= 500000) { bonusRate = 30; } else{ bonusRate = 15; } return bonusRate; } /** * @dev change the Phase from phase1 to phase2 */ function startPhase2(uint256 _startTime) public onlyOwner { require(_startTime>0); phase = Phase.PHASE2; openingTime=_startTime; } /** * @dev change the Phase from phase2 to phase3 sale */ function startPhase3(uint256 _startTime) public onlyOwner { require(0> _startTime); phase = Phase.PHASE3; openingTime=_startTime; } /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary].stage==Stage.PROCESS3_SUCCESS); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary,uint256 _stage) external onlyOwner { require(_beneficiary != address(0)); require(_stage>0); if(_stage==1){ whitelist[_beneficiary].stage=Stage.PROCESS1_FAILED; returnInvestoramount(_beneficiary,adminCharge_p1); failedWhitelist(_beneficiary); investedAmountOf[_beneficiary]=0; }else if(_stage==2){ whitelist[_beneficiary].stage=Stage.PROCESS1_SUCCESS; }else if(_stage==3){ whitelist[_beneficiary].stage=Stage.PROCESS2_FAILED; returnInvestoramount(_beneficiary,adminCharge_p2); failedWhitelist(_beneficiary); investedAmountOf[_beneficiary]=0; }else if(_stage==4){ whitelist[_beneficiary].stage=Stage.PROCESS2_SUCCESS; }else if(_stage==5){ whitelist[_beneficiary].stage=Stage.PROCESS3_FAILED; returnInvestoramount(_beneficiary,adminCharge_p3); failedWhitelist(_beneficiary); investedAmountOf[_beneficiary]=0; }else if(_stage==6){ whitelist[_beneficiary].stage=Stage.PROCESS3_SUCCESS; afterWhtelisted( _beneficiary); } } /** * @dev Withdraw tokens only after Investors added into whitelist . */ function withdrawTokens() public isWhitelisted(msg.sender) { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Change crowdsale ClosingTime * @param _endTime is End time in Seconds */ function changeEndtime(uint256 _endTime) public onlyOwner { require(_endTime > 0); closingTime = _endTime; } /** * @dev Change Token rate per ETH * @param _rate is set the current rate of AND Token */ function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); rate = _rate; emit updateRate(_rate,block.timestamp); } /** * @dev Change admin chargers * @param _p1 for first Kyc Failed-$5 * @param _p2 for second AML Failed-$7 * @param _p3 for third AI Failed-$57 */ function changeAdminCharges(uint256 _p1,uint256 _p2,uint256 _p3) public onlyOwner { require(_p1 > 0); require(_p2 > 0); require(_p3 > 0); adminCharge_p1=_p1; adminCharge_p2=_p2; adminCharge_p3=_p3; } /** * @dev Change minContribution amountAmount. * @param _minInvestment for minimum contribution ETH amount */ function changeMinInvestment(uint256 _minInvestment) public onlyOwner { require(_minInvestment > 0); minContribAmount=_minInvestment; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Checks whether the goal has been reached. * @return Whether the goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @param _to is beneficiary address * @param _value Amount if tokens * @dev tokens distribution */ function tokenDistribution(address _to, uint256 _value)public onlyOwner { require ( _to != 0x0 && _value > 0); _processPurchase(_to, _value); whitelist[_to].stage=Stage.PROCESS3_SUCCESS; } }
_wallet Vault address/
function EscrowVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; }
1,089,032
pragma solidity ^0.6.7; contract Shard { /// @notice EIP-20 token name for this token string public constant name = "Shard"; /// @notice EIP-20 token symbol for this token string public constant symbol = "SHARD"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 80_000_000e18; // 80 million Shard /// @notice Limit on the totalSupply that can be minted uint96 public constant maxSupply = 210_000_000e18; // 210 million Shard /// @notice Address which may mint new tokens address public minter; /// @notice The timestamp after which minting may occur uint public mintingAllowedAfter; /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 183 days; /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @dev Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice The EIP-712 typehash for the transfer struct used by the contract bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address to,uint256 value,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the transferWithFee struct used by the contract bytes32 public constant TRANSFER_WITH_FEE_TYPEHASH = keccak256("TransferWithFee(address to,uint256 value,uint256 fee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Shard token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability * @param mintingAllowedAfter_ The timestamp after which minting may occur */ constructor(address account, address minter_, uint mintingAllowedAfter_) public { require(mintingAllowedAfter_ >= block.timestamp, "Shard::constructor: minting can only begin after deployment"); balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter_); mintingAllowedAfter = mintingAllowedAfter_; } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Shard::setMinter: only the minter can change the minter address"); require(minter_ != address(0), "Shard::setMinter: cannot set minter to the zero address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Shard::mint: only the minter can mint"); require(block.timestamp >= mintingAllowedAfter, "Shard::mint: minting not allowed yet"); require(dst != address(0), "Shard::mint: cannot transfer to the zero address"); // record the mint mintingAllowedAfter = add256(block.timestamp, minimumTimeBetweenMints, "Shard::mint: mintingAllowedAfter overflows"); // mint the amount uint96 amount = safe96(rawAmount, "Shard::mint: amount exceeds 96 bits"); uint _totalSupply = totalSupply; require(amount <= _totalSupply / 100, "Shard::mint: amount exceeds mint allowance"); _totalSupply = add256(_totalSupply, amount, "Shard::mint: totalSupply overflows"); require(_totalSupply <= maxSupply, "Shard::mint: totalSupply exceeds maxSupply"); totalSupply = _totalSupply; // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Shard::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Burn `amount` tokens from `msg.sender` * @param rawAmount The number of tokens to burn * @return Whether or not the burn succeeded */ function burn(uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::burn: amount exceeds 96 bits"); _burnTokens(msg.sender, amount); return true; } /** * @notice Burn `amount` tokens from `src` * @param src The address of the source account * @param rawAmount The number of tokens to burn * @return Whether or not the burn succeeded */ function burnFrom(address src, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::burnFrom: amount exceeds 96 bits"); address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Shard::burnFrom: amount exceeds spender allowance"); _approve(src, spender, newAllowance); } _burnTokens(src, amount); return true; } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Shard::approve: amount exceeds 96 bits"); } _approve(msg.sender, spender, amount); return true; } /** * @notice Approve `spender` to transfer `amount` extra from `src` * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens to increase the approval by * @return Whether or not the approval succeeded */ function increaseAllowance(address spender, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::increaseAllowance: amount exceeds 96 bits"); uint96 newAllowance = add96(allowances[msg.sender][spender], amount, "Shard::increaseAllowance: allowance overflows"); _approve(msg.sender, spender, newAllowance); return true; } /** * @notice Approve `spender` to transfer `amount` less from `src` * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens to decrease the approval by * @return Whether or not the approval succeeded */ function decreaseAllowance(address spender, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::decreaseAllowance: amount exceeds 96 bits"); uint96 newAllowance = sub96(allowances[msg.sender][spender], amount, "Shard::decreaseAllowance: allowance underflows"); _approve(msg.sender, spender, newAllowance); return true; } /** * @notice Triggers an approval from owner to spender * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Shard::permit: amount exceeds 96 bits"); } require(block.timestamp <= deadline, "Shard::permit: signature expired"); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); address signatory = ecrecover(getDigest(structHash), v, r, s); require(signatory != address(0), "Shard::permit: invalid signature"); require(signatory == owner, "Shard::permit: unauthorized"); return _approve(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::transferFrom: amount exceeds 96 bits"); address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Shard::transferFrom: amount exceeds spender allowance"); _approve(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Transfer various `amount` tokens from `msg.sender` to `dsts` * @param dsts The addresses of the destination accounts * @param rawAmounts The numbers of tokens to transfer * @return Whether or not the transfers succeeded */ function transferBatch(address[] calldata dsts, uint[] calldata rawAmounts) external returns (bool) { uint length = dsts.length; require(length == rawAmounts.length, "Shard::transferBatch: calldata arrays must have the same length"); for (uint i = 0; i < length; i++) { uint96 amount = safe96(rawAmounts[i], "Shard::transferBatch: amount exceeds 96 bits"); _transferTokens(msg.sender, dsts[i], amount); } return true; } /** * @notice Transfer `amount` tokens from signatory to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function transferBySig(address dst, uint rawAmount, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { uint96 amount = safe96(rawAmount, "Shard::transferBySig: amount exceeds 96 bits"); require(block.timestamp <= expiry, "Shard::transferBySig: signature expired"); bytes32 structHash = keccak256(abi.encode(TRANSFER_TYPEHASH, dst, rawAmount, nonce, expiry)); address signatory = ecrecover(getDigest(structHash), v, r, s); require(signatory != address(0), "Shard::transferBySig: invalid signature"); require(nonce == nonces[signatory]++, "Shard::transferBySig: invalid nonce"); return _transferTokens(signatory, dst, amount); } /** * @notice Transfer `amount` tokens from signatory to `dst` with 'fee' tokens to 'feeTo' * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @param rawFee The number of tokens to transfer as fee * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param feeTo The address of the fee recipient account chosen by the msg.sender * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function transferWithFeeBySig(address dst, uint rawAmount, uint rawFee, uint nonce, uint expiry, address feeTo, uint8 v, bytes32 r, bytes32 s) external { uint96 amount = safe96(rawAmount, "Shard::transferWithFeeBySig: amount exceeds 96 bits"); uint96 fee = safe96(rawFee, "Shard::transferWithFeeBySig: fee exceeds 96 bits"); require(block.timestamp <= expiry, "Shard::transferWithFeeBySig: signature expired"); bytes32 structHash = keccak256(abi.encode(TRANSFER_WITH_FEE_TYPEHASH, dst, rawAmount, rawFee, nonce, expiry)); address signatory = ecrecover(getDigest(structHash), v, r, s); require(signatory != address(0), "Shard::transferWithFeeBySig: invalid signature"); require(nonce == nonces[signatory]++, "Shard::transferWithFeeBySig: invalid nonce"); _transferTokens(signatory, feeTo, fee); return _transferTokens(signatory, dst, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { require(block.timestamp <= expiry, "Shard::delegateBySig: signature expired"); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); address signatory = ecrecover(getDigest(structHash), v, r, s); require(signatory != address(0), "Shard::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Shard::delegateBySig: invalid nonce"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Shard::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _approve(address owner, address spender, uint96 amount) internal { allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnTokens(address src, uint96 amount) internal { require(src != address(0), "Shard::_burnTokens: cannot transfer from the zero address"); balances[src] = sub96(balances[src], amount, "Shard::_burnTokens: transfer amount exceeds balance"); totalSupply -= amount; // no case where balance exceeds totalSupply emit Transfer(src, address(0), amount); _moveDelegates(delegates[src], address(0), amount); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Shard::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Shard::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Shard::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Shard::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Shard::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Shard::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Shard::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96 c) { require((c = a + b) >= a, errorMessage); } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function add256(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256 c) { require((c = a + b) >= a, errorMessage); } function getDigest(bytes32 structHash) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), chainId, address(this))); return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
Approve `spender` to transfer `amount` extra from `src` spender The address of the account which may transfer tokens rawAmount The number of tokens to increase the approval by return Whether or not the approval succeeded/
function increaseAllowance(address spender, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Shard::increaseAllowance: amount exceeds 96 bits"); uint96 newAllowance = add96(allowances[msg.sender][spender], amount, "Shard::increaseAllowance: allowance overflows"); _approve(msg.sender, spender, newAllowance); return true; }
5,874,388
./partial_match/1/0x49a6Ff5252055c91F6e17c890A6f81374ecf9E5F/sources/MultiFunction.sol
Used to withdraw the ETH funds to the provided address/
function withdraw( address payable _to ) public isOwner { (bool success, ) = _to.call{ value: address(this).balance }(""); require(success, "ETH Transfer failed."); }
15,930,624
pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "./interfaces/IBondController.sol"; import "./interfaces/ITrancheFactory.sol"; import "./interfaces/ITranche.sol"; /** * @dev Controller for a ButtonTranche bond * * Invariants: * - `totalDebt` should always equal the sum of all tranche tokens' `totalSupply()` */ contract BondController is IBondController, OwnableUpgradeable { uint256 private constant TRANCHE_RATIO_GRANULARITY = 1000; // Denominator for basis points. Used to calculate fees uint256 private constant BPS = 10_000; // Maximum fee in terms of basis points uint256 private constant MAX_FEE_BPS = 50; // to avoid precision loss and other weird math from a small initial deposit // we require at least a minimum initial deposit uint256 private constant MINIMUM_FIRST_DEPOSIT = 10e9; address public override collateralToken; TrancheData[] public override tranches; uint256 public override trancheCount; mapping(address => bool) public trancheTokenAddresses; uint256 public maturityDate; bool public isMature; uint256 public totalDebt; // Maximum amount of collateral that can be deposited into this bond // Used as a guardrail for initial launch. // If set to 0, no deposit limit will be enforced uint256 public depositLimit; // Fee taken on deposit in basis points. Can be set by the contract owner uint256 public override feeBps; /** * @dev Constructor for Tranche ERC20 token * @param _trancheFactory The address of the tranche factory * @param _collateralToken The address of the ERC20 collateral token * @param _admin The address of the initial admin for this contract * @param trancheRatios The tranche ratios for this bond * @param _maturityDate The date timestamp in seconds at which this bond matures * @param _depositLimit The maximum amount of collateral that can be deposited. 0 if no limit */ function init( address _trancheFactory, address _collateralToken, address _admin, uint256[] memory trancheRatios, uint256 _maturityDate, uint256 _depositLimit ) external initializer { require(_trancheFactory != address(0), "BondController: invalid trancheFactory address"); require(_collateralToken != address(0), "BondController: invalid collateralToken address"); require(_admin != address(0), "BondController: invalid admin address"); __Ownable_init(); transferOwnership(_admin); trancheCount = trancheRatios.length; collateralToken = _collateralToken; string memory collateralSymbol = IERC20Metadata(collateralToken).symbol(); uint256 totalRatio; for (uint256 i = 0; i < trancheRatios.length; i++) { uint256 ratio = trancheRatios[i]; require(ratio <= TRANCHE_RATIO_GRANULARITY, "BondController: Invalid tranche ratio"); totalRatio += ratio; address trancheTokenAddress = ITrancheFactory(_trancheFactory).createTranche( getTrancheName(collateralSymbol, i, trancheRatios.length), getTrancheSymbol(collateralSymbol, i, trancheRatios.length), _collateralToken ); tranches.push(TrancheData(ITranche(trancheTokenAddress), ratio)); trancheTokenAddresses[trancheTokenAddress] = true; } require(totalRatio == TRANCHE_RATIO_GRANULARITY, "BondController: Invalid tranche ratios"); require(_maturityDate > block.timestamp, "BondController: Invalid maturity date"); maturityDate = _maturityDate; depositLimit = _depositLimit; } /** * @inheritdoc IBondController */ function deposit(uint256 amount) external override { require(amount > 0, "BondController: invalid amount"); // saving totalDebt in memory to minimize sloads uint256 _totalDebt = totalDebt; require(_totalDebt > 0 || amount >= MINIMUM_FIRST_DEPOSIT, "BondController: invalid initial amount"); require(!isMature, "BondController: Already mature"); uint256 collateralBalance = IERC20(collateralToken).balanceOf(address(this)); require(depositLimit == 0 || collateralBalance + amount <= depositLimit, "BondController: Deposit limit"); TrancheData[] memory _tranches = tranches; uint256 newDebt; uint256[] memory trancheValues = new uint256[](trancheCount); for (uint256 i = 0; i < _tranches.length; i++) { // NOTE: solidity 0.8 checks for over/underflow natively so no need for SafeMath uint256 trancheValue = (amount * _tranches[i].ratio) / TRANCHE_RATIO_GRANULARITY; // if there is any collateral, we should scale by the debt:collateral ratio if (collateralBalance > 0) { trancheValue = (trancheValue * _totalDebt) / collateralBalance; } newDebt += trancheValue; trancheValues[i] = trancheValue; } totalDebt += newDebt; TransferHelper.safeTransferFrom(collateralToken, _msgSender(), address(this), amount); // saving feeBps in memory to minimize sloads uint256 _feeBps = feeBps; for (uint256 i = 0; i < trancheValues.length; i++) { uint256 trancheValue = trancheValues[i]; // fee tranche tokens are minted and held by the contract // upon maturity, they are redeemed and underlying collateral are sent to the owner uint256 fee = (trancheValue * _feeBps) / BPS; if (fee > 0) { _tranches[i].token.mint(address(this), fee); } _tranches[i].token.mint(_msgSender(), trancheValue - fee); } emit Deposit(_msgSender(), amount, _feeBps); } /** * @inheritdoc IBondController */ function mature() external override { require(!isMature, "BondController: Already mature"); require(owner() == _msgSender() || maturityDate < block.timestamp, "BondController: Invalid call to mature"); isMature = true; TrancheData[] memory _tranches = tranches; uint256 collateralBalance = IERC20(collateralToken).balanceOf(address(this)); // Go through all tranches A-Y (not Z) delivering collateral if possible for (uint256 i = 0; i < _tranches.length - 1 && collateralBalance > 0; i++) { ITranche _tranche = _tranches[i].token; // pay out the entire tranche token's owed collateral (equal to the supply of tranche tokens) // if there is not enough collateral to pay it out, pay as much as we have uint256 amount = Math.min(_tranche.totalSupply(), collateralBalance); collateralBalance -= amount; TransferHelper.safeTransfer(collateralToken, address(_tranche), amount); // redeem fees, sending output tokens to owner _tranche.redeem(address(this), owner(), IERC20(_tranche).balanceOf(address(this))); } // Transfer any remaining collaeral to the Z tranche if (collateralBalance > 0) { ITranche _tranche = _tranches[_tranches.length - 1].token; TransferHelper.safeTransfer(collateralToken, address(_tranche), collateralBalance); _tranche.redeem(address(this), owner(), IERC20(_tranche).balanceOf(address(this))); } emit Mature(_msgSender()); } /** * @inheritdoc IBondController */ function redeemMature(address tranche, uint256 amount) external override { require(isMature, "BondController: Bond is not mature"); require(trancheTokenAddresses[tranche], "BondController: Invalid tranche address"); ITranche(tranche).redeem(_msgSender(), _msgSender(), amount); totalDebt -= amount; emit RedeemMature(_msgSender(), tranche, amount); } /** * @inheritdoc IBondController */ function redeem(uint256[] memory amounts) external override { require(!isMature, "BondController: Bond is already mature"); TrancheData[] memory _tranches = tranches; require(amounts.length == _tranches.length, "BondController: Invalid redeem amounts"); uint256 total; for (uint256 i = 0; i < amounts.length; i++) { total += amounts[i]; } for (uint256 i = 0; i < amounts.length; i++) { require( (amounts[i] * TRANCHE_RATIO_GRANULARITY) / total == _tranches[i].ratio, "BondController: Invalid redemption ratio" ); _tranches[i].token.burn(_msgSender(), amounts[i]); } uint256 collateralBalance = IERC20(collateralToken).balanceOf(address(this)); // return as a proportion of the total debt redeemed uint256 returnAmount = (total * collateralBalance) / totalDebt; totalDebt -= total; TransferHelper.safeTransfer(collateralToken, _msgSender(), returnAmount); emit Redeem(_msgSender(), amounts); } /** * @inheritdoc IBondController */ function setFee(uint256 newFeeBps) external override onlyOwner { require(!isMature, "BondController: Invalid call to setFee"); require(newFeeBps <= MAX_FEE_BPS, "BondController: New fee too high"); feeBps = newFeeBps; emit FeeUpdate(newFeeBps); } /** * @dev Get the string name for a tranche * @param collateralSymbol the symbol of the collateral token * @param index the tranche index * @param _trancheCount the total number of tranches * @return the string name of the tranche */ function getTrancheName( string memory collateralSymbol, uint256 index, uint256 _trancheCount ) internal pure returns (string memory) { return string(abi.encodePacked("ButtonTranche ", collateralSymbol, " ", getTrancheLetter(index, _trancheCount))); } /** * @dev Get the string symbol for a tranche * @param collateralSymbol the symbol of the collateral token * @param index the tranche index * @param _trancheCount the total number of tranches * @return the string symbol of the tranche */ function getTrancheSymbol( string memory collateralSymbol, uint256 index, uint256 _trancheCount ) internal pure returns (string memory) { return string(abi.encodePacked("TRANCHE-", collateralSymbol, "-", getTrancheLetter(index, _trancheCount))); } /** * @dev Get the string letter for a tranche index * @param index the tranche index * @param _trancheCount the total number of tranches * @return the string letter of the tranche index */ function getTrancheLetter(uint256 index, uint256 _trancheCount) internal pure returns (string memory) { bytes memory trancheLetters = bytes("ABCDEFGHIJKLMNOPQRSTUVWXY"); bytes memory target = new bytes(1); if (index == _trancheCount - 1) { target[0] = "Z"; } else { target[0] = trancheLetters[index]; } return string(target); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "./ITranche.sol"; struct TrancheData { ITranche token; uint256 ratio; } /** * @dev Controller for a ButtonTranche bond system */ interface IBondController { event Deposit(address from, uint256 amount, uint256 feeBps); event Mature(address caller); event RedeemMature(address user, address tranche, uint256 amount); event Redeem(address user, uint256[] amounts); event FeeUpdate(uint256 newFee); function collateralToken() external view returns (address); function tranches(uint256 i) external view returns (ITranche token, uint256 ratio); function trancheCount() external view returns (uint256 count); function feeBps() external view returns (uint256 fee); /** * @dev Deposit `amount` tokens from `msg.sender`, get tranche tokens in return * Requirements: * - `msg.sender` must have `approved` `amount` collateral tokens to this contract */ function deposit(uint256 amount) external; /** * @dev Matures the bond. Disables deposits, * fixes the redemption ratio, and distributes collateral to redemption pools * Redeems any fees collected from deposits, sending redeemed funds to the contract owner * Requirements: * - The bond is not already mature * - One of: * - `msg.sender` is owner * - `maturityDate` has passed */ function mature() external; /** * @dev Redeems some tranche tokens * Requirements: * - The bond is mature * - `msg.sender` owns at least `amount` tranche tokens from address `tranche` * - `tranche` must be a valid tranche token on this bond */ function redeemMature(address tranche, uint256 amount) external; /** * @dev Redeems a slice of tranche tokens from all tranches. * Returns collateral to the user proportionally to the amount of debt they are removing * Requirements * - The bond is not mature * - The number of `amounts` is the same as the number of tranches * - The `amounts` are in equivalent ratio to the tranche order */ function redeem(uint256[] memory amounts) external; /** * @dev Updates the fee taken on deposit to the given new fee * * Requirements * - `msg.sender` has admin role * - `newFeeBps` is in range [0, 50] */ function setFee(uint256 newFeeBps) external; } pragma solidity 0.8.3; /** * @dev Factory for Tranche minimal proxy contracts */ interface ITrancheFactory { event TrancheCreated(address newTrancheAddress); /** * @dev Deploys a minimal proxy instance for a new tranche ERC20 token with the given parameters. */ function createTranche( string memory name, string memory symbol, address _collateralToken ) external returns (address); } pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /** * @dev ERC20 token to represent a single tranche for a ButtonTranche bond * */ interface ITranche is IERC20 { /** * @dev Mint `amount` tokens to `to` * Only callable by the owner (bond controller). Used to * manage bonds, specifically creating tokens upon deposit * @param to the address to mint tokens to * @param amount The amount of tokens to mint */ function mint(address to, uint256 amount) external; /** * @dev Burn `amount` tokens from `from`'s balance * Only callable by the owner (bond controller). Used to * manage bonds, specifically burning tokens upon redemption * @param from The address to burn tokens from * @param amount The amount of tokens to burn */ function burn(address from, uint256 amount) external; /** * @dev Burn `amount` tokens from `from` and return the proportional * value of the collateral token to `to` * @param from The address to burn tokens from * @param to The address to send collateral back to * @param amount The amount of tokens to burn */ function redeem( address from, address to, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
ERC20 token to represent a single tranche for a ButtonTranche bond/
interface ITranche is IERC20 { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function redeem( address from, address to, uint256 amount ) external; } }
6,962,636
./full_match/44787/0x2Ac247f22FFaf88b1DD249D6e71d8D52a39A6F77/sources/scripts/UbeDaoContract.sol
Function to enter as contributor 0, "contrby", "contriName", "contriTitle", "email", 0xa433DF2B35F1cCA7a42a4842847205560999e7d4 Sanity checks for contributors.
function push_contributor(uint256 _idx, string memory _by, string memory _name, string memory _title, string memory _email, address _wallet_address) public { bounty storage _bounty = dao_bounties[_idx]; require(_bounty.is_bounty_closed == false, "Bounty is closed, choose a different bounty"); contributor memory _contributor; _contributor.by = _by; _contributor.name = _name; _contributor.title = _title; _contributor.email = _email; _contributor.wallet_address = _wallet_address; _bounty.contributor_list.push(_contributor); }
13,249,095
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IClaimingRegistry.sol"; import "./interfaces/IPolicyBookAdmin.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/ILeveragePortfolio.sol"; import "./interfaces/IUserLeveragePool.sol"; import "./interfaces/IPolicyQuote.sol"; import "./abstract/AbstractDependant.sol"; import "./helpers/Upgrader.sol"; import "./Globals.sol"; contract PolicyBookAdmin is IPolicyBookAdmin, OwnableUpgradeable, AbstractDependant { using Math for uint256; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; IContractsRegistry public contractsRegistry; IPolicyBookRegistry public policyBookRegistry; Upgrader internal upgrader; address private policyBookImplementationAddress; // new state variables address private policyBookFacadeImplementationAddress; address private userLeverageImplementationAddress; IClaimingRegistry internal claimingRegistry; EnumerableSet.AddressSet private _whitelistedDistributors; mapping(address => uint256) public override distributorFees; event PolicyBookWhitelisted(address policyBookAddress, bool trigger); event DistributorWhitelisted(address distributorAddress, uint256 distributorFee); event DistributorBlacklisted(address distributorAddress); event UpdatedImageURI(uint256 claimIndex, string oldImageUri, string newImageUri); uint256 public constant MAX_DISTRIBUTOR_FEE = 20 * PRECISION; // new state post v2 deployment IPolicyQuote public policyQuote; function __PolicyBookAdmin_init( address _policyBookImplementationAddress, address _policyBookFacadeImplementationAddress, address _userLeverageImplementationAddress ) external initializer { require(_policyBookImplementationAddress != address(0), "PBA: PB Zero address"); require(_policyBookFacadeImplementationAddress != address(0), "PBA: PBF Zero address"); require(_userLeverageImplementationAddress != address(0), "PBA: PBF Zero address"); __Ownable_init(); upgrader = new Upgrader(); policyBookImplementationAddress = _policyBookImplementationAddress; policyBookFacadeImplementationAddress = _policyBookFacadeImplementationAddress; userLeverageImplementationAddress = _userLeverageImplementationAddress; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { contractsRegistry = _contractsRegistry; policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract()); policyQuote = IPolicyQuote(_contractsRegistry.getPolicyQuoteContract()); } function injectDependenciesToExistingPolicies( uint256 offset, uint256 limit, PoolTypes _poolType ) external onlyOwner { address[] memory _policies = policyBookRegistry.list(offset, limit); IContractsRegistry _contractsRegistry = contractsRegistry; uint256 to = (offset.add(limit)).min(_policies.length).max(offset); for (uint256 i = offset; i < to; i++) { address _pool; if (_poolType == PoolTypes.POLICY_BOOK || _poolType == PoolTypes.POLICY_FACADE) { if (policyBookRegistry.isUserLeveragePool(_policies[i])) continue; _pool = _policies[i]; if (_poolType == PoolTypes.POLICY_FACADE) { IPolicyBook _policyBook = IPolicyBook(_pool); _pool = address(_policyBook.policyBookFacade()); } } else { if (!policyBookRegistry.isUserLeveragePool(_policies[i])) continue; _pool = _policies[i]; } AbstractDependant dependant = AbstractDependant(_pool); if (dependant.injector() == address(0)) { dependant.setInjector(address(this)); } dependant.setDependencies(_contractsRegistry); } } function getUpgrader() external view override returns (address) { require(address(upgrader) != address(0), "PolicyBookAdmin: Bad upgrader"); return address(upgrader); } function getImplementationOfPolicyBook(address policyBookAddress) external override returns (address) { require( policyBookRegistry.isPolicyBook(policyBookAddress), "PolicyBookAdmin: Not a PolicyBook" ); return upgrader.getImplementation(policyBookAddress); } function getImplementationOfPolicyBookFacade(address policyBookFacadeAddress) external override returns (address) { require( policyBookRegistry.isPolicyBookFacade(policyBookFacadeAddress), "PolicyBookAdmin: Not a PolicyBookFacade" ); return upgrader.getImplementation(policyBookFacadeAddress); } function getCurrentPolicyBooksImplementation() external view override returns (address) { return policyBookImplementationAddress; } function getCurrentPolicyBooksFacadeImplementation() external view override returns (address) { return policyBookFacadeImplementationAddress; } function getCurrentUserLeverageImplementation() external view override returns (address) { return userLeverageImplementationAddress; } function _setPolicyBookImplementation(address policyBookImpl) internal { if (policyBookImplementationAddress != policyBookImpl) { policyBookImplementationAddress = policyBookImpl; } } function _setPolicyBookFacadeImplementation(address policyBookFacadeImpl) internal { if (policyBookFacadeImplementationAddress != policyBookFacadeImpl) { policyBookFacadeImplementationAddress = policyBookFacadeImpl; } } function _setUserLeverageImplementation(address userLeverageImpl) internal { if (userLeverageImplementationAddress != userLeverageImpl) { userLeverageImplementationAddress = userLeverageImpl; } } function upgradePolicyBooks( address policyBookImpl, uint256 offset, uint256 limit ) external onlyOwner { _upgradePolicyBooks(policyBookImpl, offset, limit, ""); } /// @notice can only call functions that have no parameters function upgradePolicyBooksAndCall( address policyBookImpl, uint256 offset, uint256 limit, string calldata functionSignature ) external onlyOwner { _upgradePolicyBooks(policyBookImpl, offset, limit, functionSignature); } function _upgradePolicyBooks( address policyBookImpl, uint256 offset, uint256 limit, string memory functionSignature ) internal { require(policyBookImpl != address(0), "PolicyBookAdmin: Zero address"); require(Address.isContract(policyBookImpl), "PolicyBookAdmin: Invalid address"); _setPolicyBookImplementation(policyBookImpl); address[] memory _policies = policyBookRegistry.list(offset, limit); for (uint256 i = 0; i < _policies.length; i++) { if (!policyBookRegistry.isUserLeveragePool(_policies[i])) { if (bytes(functionSignature).length > 0) { upgrader.upgradeAndCall( _policies[i], policyBookImpl, abi.encodeWithSignature(functionSignature) ); } else { upgrader.upgrade(_policies[i], policyBookImpl); } } } } function upgradePolicyBookFacades( address policyBookFacadeImpl, uint256 offset, uint256 limit ) external onlyOwner { _upgradePolicyBookFacades(policyBookFacadeImpl, offset, limit, ""); } /// @notice can only call functions that have no parameters function upgradePolicyBookFacadesAndCall( address policyBookFacadeImpl, uint256 offset, uint256 limit, string calldata functionSignature ) external onlyOwner { _upgradePolicyBookFacades(policyBookFacadeImpl, offset, limit, functionSignature); } function _upgradePolicyBookFacades( address policyBookFacadeImpl, uint256 offset, uint256 limit, string memory functionSignature ) internal { require(policyBookFacadeImpl != address(0), "PolicyBookAdmin: Zero address"); require(Address.isContract(policyBookFacadeImpl), "PolicyBookAdmin: Invalid address"); _setPolicyBookFacadeImplementation(policyBookFacadeImpl); address[] memory _policies = policyBookRegistry.list(offset, limit); for (uint256 i = 0; i < _policies.length; i++) { if (!policyBookRegistry.isUserLeveragePool(_policies[i])) { IPolicyBook _policyBook = IPolicyBook(_policies[i]); address policyBookFacade = address(IPolicyBookFacade(_policyBook.policyBookFacade())); if (bytes(functionSignature).length > 0) { upgrader.upgradeAndCall( policyBookFacade, policyBookFacadeImpl, abi.encodeWithSignature(functionSignature) ); } else { upgrader.upgrade(policyBookFacade, policyBookFacadeImpl); } } } } /// TODO refactor all upgrades function in one function function upgradeUserLeveragePools( address userLeverageImpl, uint256 offset, uint256 limit ) external onlyOwner { _upgradeUserLeveragePools(userLeverageImpl, offset, limit, ""); } /// @notice can only call functions that have no parameters function upgradeUserLeveragePoolsAndCall( address userLeverageImpl, uint256 offset, uint256 limit, string calldata functionSignature ) external onlyOwner { _upgradeUserLeveragePools(userLeverageImpl, offset, limit, functionSignature); } function _upgradeUserLeveragePools( address userLeverageImpl, uint256 offset, uint256 limit, string memory functionSignature ) internal { require(userLeverageImpl != address(0), "PolicyBookAdmin: Zero address"); require(Address.isContract(userLeverageImpl), "PolicyBookAdmin: Invalid address"); _setUserLeverageImplementation(userLeverageImpl); address[] memory _policies = policyBookRegistry.listByType(IPolicyBookFabric.ContractType.VARIOUS, offset, limit); for (uint256 i = 0; i < _policies.length; i++) { if (policyBookRegistry.isUserLeveragePool(_policies[i])) { if (bytes(functionSignature).length > 0) { upgrader.upgradeAndCall( _policies[i], userLeverageImpl, abi.encodeWithSignature(functionSignature) ); } else { upgrader.upgrade(_policies[i], userLeverageImpl); } } } } /// @notice It blacklists or whitelists a PolicyBook. Only whitelisted PolicyBooks can /// receive stakes and funds /// @param policyBookAddress PolicyBook address that will be whitelisted or blacklisted /// @param whitelisted true to whitelist or false to blacklist a PolicyBook function whitelist(address policyBookAddress, bool whitelisted) public override onlyOwner { require(policyBookRegistry.isPolicyBook(policyBookAddress), "PolicyBookAdmin: Not a PB"); IPolicyBook(policyBookAddress).whitelist(whitelisted); policyBookRegistry.whitelist(policyBookAddress, whitelisted); emit PolicyBookWhitelisted(policyBookAddress, whitelisted); } /// @notice Whitelist distributor address and respective fees /// @param _distributor distributor address that will receive funds /// @param _distributorFee distributor fee amount (passed with its precision : _distributorFee * 10**25) function whitelistDistributor(address _distributor, uint256 _distributorFee) external override onlyOwner { require(_distributor != address(0), "PBAdmin: Null is forbidden"); require(_distributorFee > 0, "PBAdmin: Fee cannot be 0"); require(_distributorFee <= MAX_DISTRIBUTOR_FEE, "PBAdmin: Fee is over max cap"); _whitelistedDistributors.add(_distributor); distributorFees[_distributor] = _distributorFee; emit DistributorWhitelisted(_distributor, _distributorFee); } /// @notice Removes a distributor address from the distributor whitelist /// @param _distributor distributor address that will be blacklist function blacklistDistributor(address _distributor) external override onlyOwner { _whitelistedDistributors.remove(_distributor); delete distributorFees[_distributor]; emit DistributorBlacklisted(_distributor); } /// @notice Distributor commission fee is 2-5% of the Premium. /// It comes from the Protocol’s fee part /// @param _distributor address of the distributor /// @return true if address is a whitelisted distributor function isWhitelistedDistributor(address _distributor) external view override returns (bool) { return _whitelistedDistributors.contains(_distributor); } function listDistributors(uint256 offset, uint256 limit) external view override returns (address[] memory _distributors, uint256[] memory _distributorsFees) { return _listDistributors(offset, limit, _whitelistedDistributors); } /// @notice Used to get a list of whitelisted distributors /// @return _distributors a list containing distritubors addresses /// @return _distributorsFees a list containing distritubors fees function _listDistributors( uint256 offset, uint256 limit, EnumerableSet.AddressSet storage set ) internal view returns (address[] memory _distributors, uint256[] memory _distributorsFees) { uint256 to = (offset.add(limit)).min(set.length()).max(offset); _distributors = new address[](to - offset); _distributorsFees = new uint256[](to - offset); for (uint256 i = offset; i < to; i++) { _distributors[i - offset] = set.at(i); _distributorsFees[i - offset] = distributorFees[_distributors[i]]; } } function countDistributors() external view override returns (uint256) { return _whitelistedDistributors.length(); } function whitelistBatch(address[] calldata policyBooksAddresses, bool[] calldata whitelists) external onlyOwner { require( policyBooksAddresses.length == whitelists.length, "PolicyBookAdmin: Length mismatch" ); for (uint256 i = 0; i < policyBooksAddresses.length; i++) { whitelist(policyBooksAddresses[i], whitelists[i]); } } /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) public onlyOwner { IClaimingRegistry.ClaimInfo memory claimInfo = claimingRegistry.claimInfo(_claimIndex); string memory oldEvidenceURI = claimInfo.evidenceURI; claimingRegistry.updateImageUriOfClaim(_claimIndex, _newEvidenceURI); emit UpdatedImageURI(_claimIndex, oldEvidenceURI, _newEvidenceURI); } /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _userLeverageMPL uint256 value of the user leverage mpl; /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage mpl function setPolicyBookFacadeMPLs( address _facadeAddress, uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL ) external override onlyOwner { IPolicyBookFacade(_facadeAddress).setMPLs(_userLeverageMPL, _reinsuranceLeverageMPL); } /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _newRebalancingThreshold uint256 value of the reinsurance leverage mpl function setPolicyBookFacadeRebalancingThreshold( address _facadeAddress, uint256 _newRebalancingThreshold ) external override onlyOwner { IPolicyBookFacade(_facadeAddress).setRebalancingThreshold(_newRebalancingThreshold); } /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setPolicyBookFacadeSafePricingModel(address _facadeAddress, bool _safePricingModel) external override onlyOwner { IPolicyBookFacade(_facadeAddress).setSafePricingModel(_safePricingModel); } /// @notice sets the user leverage pool Rebalancing Threshold /// @param _LeveragePoolAddress address of the user leverage pool or reinsurance pool /// @param _newRebalancingThreshold uint256 value of Rebalancing Threshold function setLeveragePortfolioRebalancingThreshold( address _LeveragePoolAddress, uint256 _newRebalancingThreshold ) external override onlyOwner { ILeveragePortfolio(_LeveragePoolAddress).setRebalancingThreshold(_newRebalancingThreshold); } function setLeveragePortfolioProtocolConstant( address _LeveragePoolAddress, uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a1_ProtocolConstant, uint256 _max_ProtocolConstant ) external override onlyOwner { ILeveragePortfolio(_LeveragePoolAddress).setProtocolConstant( _targetUR, _d_ProtocolConstant, _a1_ProtocolConstant, _max_ProtocolConstant ); } function setUserLeverageMaxCapacities(address _userLeverageAddress, uint256 _maxCapacities) external override onlyOwner { IUserLeveragePool(_userLeverageAddress).setMaxCapacities(_maxCapacities); } function setUserLeverageA2_ProtocolConstant( address _userLeverageAddress, uint256 _a2_ProtocolConstant ) external override onlyOwner { IUserLeveragePool(_userLeverageAddress).setA2_ProtocolConstant(_a2_ProtocolConstant); } /// @notice setup all pricing model varlues ///@param _highRiskRiskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is considered risky, % ///@param _lowRiskRiskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is not considered risky, % ///@param _highRiskMinimumCostPercentage MC minimum cost of cover (Premium) when the assets is considered risky, %; ///@param _lowRiskMinimumCostPercentage MC minimum cost of cover (Premium), when the assets is not considered risky, % ///@param _minimumInsuranceCost minimum cost of insurance (Premium) , (10**18) ///@param _lowRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is not considered risky (Premium) ///@param _lowRiskMaxPercentPremiumCost100Utilization MCI not risky ///@param _highRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is considered risky (Premium) ///@param _highRiskMaxPercentPremiumCost100Utilization MCI risky function setupPricingModel( uint256 _highRiskRiskyAssetThresholdPercentage, uint256 _lowRiskRiskyAssetThresholdPercentage, uint256 _highRiskMinimumCostPercentage, uint256 _lowRiskMinimumCostPercentage, uint256 _minimumInsuranceCost, uint256 _lowRiskMaxPercentPremiumCost, uint256 _lowRiskMaxPercentPremiumCost100Utilization, uint256 _highRiskMaxPercentPremiumCost, uint256 _highRiskMaxPercentPremiumCost100Utilization ) external override onlyOwner { policyQuote.setupPricingModel( _highRiskRiskyAssetThresholdPercentage, _lowRiskRiskyAssetThresholdPercentage, _highRiskMinimumCostPercentage, _lowRiskMinimumCostPercentage, _minimumInsuranceCost, _lowRiskMaxPercentPremiumCost, _lowRiskMaxPercentPremiumCost100Utilization, _highRiskMaxPercentPremiumCost, _highRiskMaxPercentPremiumCost100Utilization ); } }
Update Image Uri in case it contains material that is ilegal or offensive. Only the owner can erase/update evidenceUri. _claimIndex Claim Index that is going to be updated _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) public onlyOwner { IClaimingRegistry.ClaimInfo memory claimInfo = claimingRegistry.claimInfo(_claimIndex); string memory oldEvidenceURI = claimInfo.evidenceURI; claimingRegistry.updateImageUriOfClaim(_claimIndex, _newEvidenceURI); emit UpdatedImageURI(_claimIndex, oldEvidenceURI, _newEvidenceURI); }
930,105
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; // Inheritance import "./Owned.sol"; import "./MixinSystemSettings.sol"; import "./interfaces/ICollateralLoan.sol"; // Libraries import "./SafeDecimalMath.sol"; // Internal references import "./CollateralState.sol"; import "./interfaces/ICollateralManager.sol"; import "./interfaces/ISystemStatus.sol"; import "./interfaces/IFeePool.sol"; import "./interfaces/ISynth.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/IShortingRewards.sol"; contract Collateral is ICollateralLoan, Owned, MixinSystemSettings { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== CONSTANTS ========== */ bytes32 private constant sUSD = "sUSD"; // ========== STATE VARIABLES ========== // The synth corresponding to the collateral. bytes32 public collateralKey; // Stores loans CollateralState public state; address public manager; // The synths that this contract can issue. bytes32[] public synths; // Map from currency key to synth contract name. mapping(bytes32 => bytes32) public synthsByKey; // Map from currency key to the shorting rewards contract mapping(bytes32 => address) public shortingRewards; // ========== SETTER STATE VARIABLES ========== // The minimum collateral ratio required to avoid liquidation. uint public minCratio; // The minimum amount of collateral to create a loan. uint public minCollateral; // The fee charged for issuing a loan. uint public issueFeeRate; // The maximum number of loans that an account can create with this collateral. uint public maxLoansPerAccount = 50; // Time in seconds that a user must wait between interacting with a loan. // Provides front running and flash loan protection. uint public interactionDelay = 300; bool public canOpenLoans = true; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; bytes32 private constant CONTRACT_SYNTHSUSD = "SynthsUSD"; /* ========== CONSTRUCTOR ========== */ constructor( CollateralState _state, address _owner, address _manager, address _resolver, bytes32 _collateralKey, uint _minCratio, uint _minCollateral ) public Owned(_owner) MixinSystemSettings(_resolver) { manager = _manager; state = _state; collateralKey = _collateralKey; minCratio = _minCratio; minCollateral = _minCollateral; } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](5); newAddresses[0] = CONTRACT_FEEPOOL; newAddresses[1] = CONTRACT_EXRATES; newAddresses[2] = CONTRACT_EXCHANGER; newAddresses[3] = CONTRACT_SYSTEMSTATUS; newAddresses[4] = CONTRACT_SYNTHSUSD; bytes32[] memory combined = combineArrays(existingAddresses, newAddresses); addresses = combineArrays(combined, synths); } /* ---------- Related Contracts ---------- */ function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function _synth(bytes32 synthName) internal view returns (ISynth) { return ISynth(requireAndGetAddress(synthName)); } function _synthsUSD() internal view returns (ISynth) { return ISynth(requireAndGetAddress(CONTRACT_SYNTHSUSD)); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function _exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function _feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function _manager() internal view returns (ICollateralManager) { return ICollateralManager(manager); } /* ---------- Public Views ---------- */ function collateralRatio(Loan memory loan) public view returns (uint cratio) { uint cvalue = _exchangeRates().effectiveValue(collateralKey, loan.collateral, sUSD); uint dvalue = _exchangeRates().effectiveValue(loan.currency, loan.amount.add(loan.accruedInterest), sUSD); cratio = cvalue.divideDecimal(dvalue); } // The maximum number of synths issuable for this amount of collateral function maxLoan(uint amount, bytes32 currency) public view returns (uint max) { max = issuanceRatio().multiplyDecimal(_exchangeRates().effectiveValue(collateralKey, amount, currency)); } /** * r = target issuance ratio * D = debt value in sUSD * V = collateral value in sUSD * P = liquidation penalty * Calculates amount of synths = (D - V * r) / (1 - (1 + P) * r) * Note: if you pass a loan in here that is not eligible for liquidation it will revert. * We check the ratio first in liquidateInternal and only pass eligible loans in. */ function liquidationAmount(Loan memory loan) public view returns (uint amount) { uint liquidationPenalty = getLiquidationPenalty(); uint debtValue = _exchangeRates().effectiveValue(loan.currency, loan.amount.add(loan.accruedInterest), sUSD); uint collateralValue = _exchangeRates().effectiveValue(collateralKey, loan.collateral, sUSD); uint unit = SafeDecimalMath.unit(); uint dividend = debtValue.sub(collateralValue.divideDecimal(minCratio)); uint divisor = unit.sub(unit.add(liquidationPenalty).divideDecimal(minCratio)); uint sUSDamount = dividend.divideDecimal(divisor); return _exchangeRates().effectiveValue(sUSD, sUSDamount, loan.currency); } // amount is the amount of synths we are liquidating function collateralRedeemed(bytes32 currency, uint amount) public view returns (uint collateral) { uint liquidationPenalty = getLiquidationPenalty(); collateral = _exchangeRates().effectiveValue(currency, amount, collateralKey); collateral = collateral.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty)); } function areSynthsAndCurrenciesSet(bytes32[] calldata _synthNamesInResolver, bytes32[] calldata _synthKeys) external view returns (bool) { if (synths.length != _synthNamesInResolver.length) { return false; } for (uint i = 0; i < _synthNamesInResolver.length; i++) { bytes32 synthName = _synthNamesInResolver[i]; if (synths[i] != synthName) { return false; } if (synthsByKey[_synthKeys[i]] != synths[i]) { return false; } } return true; } /* ---------- UTILITIES ---------- */ // Check the account has enough of the synth to make the payment function _checkSynthBalance( address payer, bytes32 key, uint amount ) internal view { require(IERC20(address(_synth(synthsByKey[key]))).balanceOf(payer) >= amount, "Not enough synth balance"); } // We set the interest index to 0 to indicate the loan has been closed. function _checkLoanAvailable(Loan memory _loan) internal view { require(_loan.interestIndex > 0, "Loan does not exist"); require(_loan.lastInteraction.add(interactionDelay) <= block.timestamp, "Loan recently interacted with"); } function issuanceRatio() internal view returns (uint ratio) { ratio = SafeDecimalMath.unit().divideDecimalRound(minCratio); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Synths ---------- */ function addSynths(bytes32[] calldata _synthNamesInResolver, bytes32[] calldata _synthKeys) external onlyOwner { require(_synthNamesInResolver.length == _synthKeys.length, "Input array length mismatch"); for (uint i = 0; i < _synthNamesInResolver.length; i++) { bytes32 synthName = _synthNamesInResolver[i]; synths.push(synthName); synthsByKey[_synthKeys[i]] = synthName; } // ensure cache has the latest rebuildCache(); } /* ---------- Rewards Contracts ---------- */ function addRewardsContracts(address rewardsContract, bytes32 synth) external onlyOwner { shortingRewards[synth] = rewardsContract; } /* ---------- SETTERS ---------- */ function setMinCratio(uint _minCratio) external onlyOwner { require(_minCratio > SafeDecimalMath.unit(), "Must be greater than 1"); minCratio = _minCratio; emit MinCratioRatioUpdated(minCratio); } function setIssueFeeRate(uint _issueFeeRate) external onlyOwner { issueFeeRate = _issueFeeRate; emit IssueFeeRateUpdated(issueFeeRate); } function setInteractionDelay(uint _interactionDelay) external onlyOwner { require(_interactionDelay <= SafeDecimalMath.unit() * 3600, "Max 1 hour"); interactionDelay = _interactionDelay; emit InteractionDelayUpdated(interactionDelay); } function setManager(address _newManager) external onlyOwner { manager = _newManager; emit ManagerUpdated(manager); } function setCanOpenLoans(bool _canOpenLoans) external onlyOwner { canOpenLoans = _canOpenLoans; emit CanOpenLoansUpdated(canOpenLoans); } /* ---------- LOAN INTERACTIONS ---------- */ function openInternal( uint collateral, uint amount, bytes32 currency, bool short ) internal rateIsValid returns (uint id) { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); require(canOpenLoans, "Opening is disabled"); // 1. We can only issue certain synths. require(synthsByKey[currency] > 0, "Not allowed to issue this synth"); // 2. Make sure the synth rate is not invalid. require(!_exchangeRates().rateIsInvalid(currency), "Currency rate is invalid"); // 3. Collateral >= minimum collateral size. require(collateral >= minCollateral, "Not enough collateral to open"); // 4. Cap the number of loans so that the array doesn't get too big. require(state.getNumLoans(msg.sender) < maxLoansPerAccount, "Max loans exceeded"); // 5. Check we haven't hit the debt cap for non snx collateral. (bool canIssue, bool anyRateIsInvalid) = _manager().exceedsDebtLimit(amount, currency); require(canIssue && !anyRateIsInvalid, "Debt limit or invalid rate"); // 6. Require requested loan < max loan require(amount <= maxLoan(collateral, currency), "Exceeds max borrowing power"); // 7. This fee is denominated in the currency of the loan uint issueFee = amount.multiplyDecimalRound(issueFeeRate); // 8. Calculate the minting fee and subtract it from the loan amount uint loanAmountMinusFee = amount.sub(issueFee); // 9. Get a Loan ID id = _manager().getNewLoanId(); // 10. Create the loan struct. Loan memory loan = Loan({ id: id, account: msg.sender, collateral: collateral, currency: currency, amount: amount, short: short, accruedInterest: 0, interestIndex: 0, lastInteraction: block.timestamp }); // 11. Accrue interest on the loan. loan = accrueInterest(loan); // 12. Save the loan to storage state.createLoan(loan); // 13. Pay the minting fees to the fee pool _payFees(issueFee, currency); // 14. If its short, convert back to sUSD, otherwise issue the loan. if (short) { _synthsUSD().issue(msg.sender, _exchangeRates().effectiveValue(currency, loanAmountMinusFee, sUSD)); _manager().incrementShorts(currency, amount); if (shortingRewards[currency] != address(0)) { IShortingRewards(shortingRewards[currency]).enrol(msg.sender, amount); } } else { _synth(synthsByKey[currency]).issue(msg.sender, loanAmountMinusFee); _manager().incrementLongs(currency, amount); } // 15. Emit event emit LoanCreated(msg.sender, id, amount, collateral, currency, issueFee); } function closeInternal(address borrower, uint id) internal rateIsValid returns (uint collateral) { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); // 1. Get the loan. Loan memory loan = state.getLoan(borrower, id); // 2. Check loan is open and the last interaction time. _checkLoanAvailable(loan); // 3. Accrue interest on the loan. loan = accrueInterest(loan); // 4. Work out the total amount owing on the loan. uint total = loan.amount.add(loan.accruedInterest); // 5. Check they have enough balance to close the loan. _checkSynthBalance(loan.account, loan.currency, total); // 6. Burn the synths require( !_exchanger().hasWaitingPeriodOrSettlementOwing(borrower, loan.currency), "Waiting secs or settlement owing" ); _synth(synthsByKey[loan.currency]).burn(borrower, total); // 7. Tell the manager. if (loan.short) { _manager().decrementShorts(loan.currency, loan.amount); if (shortingRewards[loan.currency] != address(0)) { IShortingRewards(shortingRewards[loan.currency]).withdraw(borrower, loan.amount); } } else { _manager().decrementLongs(loan.currency, loan.amount); } // 8. Assign the collateral to be returned. collateral = loan.collateral; // 9. Pay fees _payFees(loan.accruedInterest, loan.currency); // 10. Record loan as closed loan.amount = 0; loan.collateral = 0; loan.accruedInterest = 0; loan.interestIndex = 0; loan.lastInteraction = block.timestamp; state.updateLoan(loan); // 11. Emit the event emit LoanClosed(borrower, id); } function closeByLiquidationInternal( address borrower, address liquidator, Loan memory loan ) internal returns (uint collateral) { // 1. Work out the total amount owing on the loan. uint total = loan.amount.add(loan.accruedInterest); // 2. Store this for the event. uint amount = loan.amount; // 3. Return collateral to the child class so it knows how much to transfer. collateral = loan.collateral; // 4. Burn the synths require(!_exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, loan.currency), "Waiting or settlement owing"); _synth(synthsByKey[loan.currency]).burn(liquidator, total); // 5. Tell the manager. if (loan.short) { _manager().decrementShorts(loan.currency, loan.amount); if (shortingRewards[loan.currency] != address(0)) { IShortingRewards(shortingRewards[loan.currency]).withdraw(borrower, loan.amount); } } else { _manager().decrementLongs(loan.currency, loan.amount); } // 6. Pay fees _payFees(loan.accruedInterest, loan.currency); // 7. Record loan as closed loan.amount = 0; loan.collateral = 0; loan.accruedInterest = 0; loan.interestIndex = 0; loan.lastInteraction = block.timestamp; state.updateLoan(loan); // 8. Emit the event. emit LoanClosedByLiquidation(borrower, loan.id, liquidator, amount, collateral); } function depositInternal( address account, uint id, uint amount ) internal rateIsValid { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); // 1. They sent some value > 0 require(amount > 0, "Deposit must be greater than 0"); // 2. Get the loan Loan memory loan = state.getLoan(account, id); // 3. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 4. Accrue interest loan = accrueInterest(loan); // 5. Add the collateral loan.collateral = loan.collateral.add(amount); // 6. Update the last interaction time. loan.lastInteraction = block.timestamp; // 7. Store the loan state.updateLoan(loan); // 8. Emit the event emit CollateralDeposited(account, id, amount, loan.collateral); } function withdrawInternal(uint id, uint amount) internal rateIsValid returns (uint withdraw) { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); // 1. Get the loan. Loan memory loan = state.getLoan(msg.sender, id); // 2. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 3. Accrue interest. loan = accrueInterest(loan); // 4. Subtract the collateral. loan.collateral = loan.collateral.sub(amount); // 5. Update the last interaction time. loan.lastInteraction = block.timestamp; // 6. Check that the new amount does not put them under the minimum c ratio. require(collateralRatio(loan) > minCratio, "Cratio too low"); // 7. Store the loan. state.updateLoan(loan); // 8. Assign the return variable. withdraw = amount; // 9. Emit the event. emit CollateralWithdrawn(msg.sender, id, amount, loan.collateral); } function liquidateInternal( address borrower, uint id, uint payment ) internal rateIsValid returns (uint collateralLiquidated) { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); // 1. Check the payment amount. require(payment > 0, "Payment must be greater than 0"); // 2. Get the loan. Loan memory loan = state.getLoan(borrower, id); // 3. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 4. Accrue interest. loan = accrueInterest(loan); // 5. Check they have enough balance to make the payment. _checkSynthBalance(msg.sender, loan.currency, payment); // 6. Check they are eligible for liquidation. require(collateralRatio(loan) < minCratio, "Cratio above liquidation ratio"); // 7. Determine how much needs to be liquidated to fix their c ratio. uint liqAmount = liquidationAmount(loan); // 8. Only allow them to liquidate enough to fix the c ratio. uint amountToLiquidate = liqAmount < payment ? liqAmount : payment; // 9. Work out the total amount owing on the loan. uint amountOwing = loan.amount.add(loan.accruedInterest); // 10. If its greater than the amount owing, we need to close the loan. if (amountToLiquidate >= amountOwing) { return closeByLiquidationInternal(borrower, msg.sender, loan); } // 11. Process the payment to workout interest/principal split. loan = _processPayment(loan, amountToLiquidate); // 12. Work out how much collateral to redeem. collateralLiquidated = collateralRedeemed(loan.currency, amountToLiquidate); loan.collateral = loan.collateral.sub(collateralLiquidated); // 13. Update the last interaction time. loan.lastInteraction = block.timestamp; // 14. Burn the synths from the liquidator. require(!_exchanger().hasWaitingPeriodOrSettlementOwing(msg.sender, loan.currency), "Waiting or settlement owing"); _synth(synthsByKey[loan.currency]).burn(msg.sender, amountToLiquidate); // 15. Store the loan. state.updateLoan(loan); // 16. Emit the event emit LoanPartiallyLiquidated(borrower, id, msg.sender, amountToLiquidate, collateralLiquidated); } function repayInternal( address borrower, address repayer, uint id, uint payment ) internal rateIsValid { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); // 1. Check the payment amount. require(payment > 0, "Payment must be greater than 0"); // 2. Get loan Loan memory loan = state.getLoan(borrower, id); // 3. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 4. Accrue interest. loan = accrueInterest(loan); // 5. Check the spender has enough synths to make the repayment _checkSynthBalance(repayer, loan.currency, payment); // 6. Process the payment. loan = _processPayment(loan, payment); // 7. Update the last interaction time. loan.lastInteraction = block.timestamp; // 8. Burn synths from the payer require(!_exchanger().hasWaitingPeriodOrSettlementOwing(repayer, loan.currency), "Waiting or settlement owing"); _synth(synthsByKey[loan.currency]).burn(repayer, payment); // 9. Store the loan state.updateLoan(loan); // 10. Emit the event. emit LoanRepaymentMade(borrower, repayer, id, payment, loan.amount); } function drawInternal(uint id, uint amount) internal rateIsValid { // 0. Check the system is active. _systemStatus().requireIssuanceActive(); // 1. Get loan. Loan memory loan = state.getLoan(msg.sender, id); // 2. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 3. Accrue interest. loan = accrueInterest(loan); // 4. Add the requested amount. loan.amount = loan.amount.add(amount); // 5. If it is below the minimum, don't allow this draw. require(collateralRatio(loan) > minCratio, "Cannot draw this much"); // 6. This fee is denominated in the currency of the loan uint issueFee = amount.multiplyDecimalRound(issueFeeRate); // 7. Calculate the minting fee and subtract it from the draw amount uint amountMinusFee = amount.sub(issueFee); // 8. If its short, let the child handle it, otherwise issue the synths. if (loan.short) { _manager().incrementShorts(loan.currency, amount); _synthsUSD().issue(msg.sender, _exchangeRates().effectiveValue(loan.currency, amountMinusFee, sUSD)); if (shortingRewards[loan.currency] != address(0)) { IShortingRewards(shortingRewards[loan.currency]).enrol(msg.sender, amount); } } else { _manager().incrementLongs(loan.currency, amount); _synth(synthsByKey[loan.currency]).issue(msg.sender, amountMinusFee); } // 9. Pay the minting fees to the fee pool _payFees(issueFee, loan.currency); // 10. Update the last interaction time. loan.lastInteraction = block.timestamp; // 11. Store the loan state.updateLoan(loan); // 12. Emit the event. emit LoanDrawnDown(msg.sender, id, amount); } // Update the cumulative interest rate for the currency that was interacted with. function accrueInterest(Loan memory loan) internal returns (Loan memory loanAfter) { loanAfter = loan; // 1. Get the rates we need. (uint entryRate, uint lastRate, uint lastUpdated, uint newIndex) = loan.short ? _manager().getShortRatesAndTime(loan.currency, loan.interestIndex) : _manager().getRatesAndTime(loan.interestIndex); // 2. Get the instantaneous rate. (uint rate, bool invalid) = loan.short ? _manager().getShortRate(synthsByKey[loan.currency]) : _manager().getBorrowRate(); require(!invalid, "Rates are invalid"); // 3. Get the time since we last updated the rate. uint timeDelta = block.timestamp.sub(lastUpdated).mul(SafeDecimalMath.unit()); // 4. Get the latest cumulative rate. F_n+1 = F_n + F_last uint latestCumulative = lastRate.add(rate.multiplyDecimal(timeDelta)); // 5. If the loan was just opened, don't record any interest. Otherwise multiple by the amount outstanding. uint interest = loan.interestIndex == 0 ? 0 : loan.amount.multiplyDecimal(latestCumulative.sub(entryRate)); // 7. Update rates with the lastest cumulative rate. This also updates the time. loan.short ? _manager().updateShortRates(loan.currency, latestCumulative) : _manager().updateBorrowRates(latestCumulative); // 8. Update loan loanAfter.accruedInterest = loan.accruedInterest.add(interest); loanAfter.interestIndex = newIndex; state.updateLoan(loanAfter); } // Works out the amount of interest and principal after a repayment is made. function _processPayment(Loan memory loanBefore, uint payment) internal returns (Loan memory loanAfter) { loanAfter = loanBefore; if (payment > 0 && loanBefore.accruedInterest > 0) { uint interestPaid = payment > loanBefore.accruedInterest ? loanBefore.accruedInterest : payment; loanAfter.accruedInterest = loanBefore.accruedInterest.sub(interestPaid); payment = payment.sub(interestPaid); _payFees(interestPaid, loanBefore.currency); } // If there is more payment left after the interest, pay down the principal. if (payment > 0) { loanAfter.amount = loanBefore.amount.sub(payment); // And get the manager to reduce the total long/short balance. if (loanAfter.short) { _manager().decrementShorts(loanAfter.currency, payment); if (shortingRewards[loanAfter.currency] != address(0)) { IShortingRewards(shortingRewards[loanAfter.currency]).withdraw(loanAfter.account, payment); } } else { _manager().decrementLongs(loanAfter.currency, payment); } } } // Take an amount of fees in a certain synth and convert it to sUSD before paying the fee pool. function _payFees(uint amount, bytes32 synth) internal { if (amount > 0) { if (synth != sUSD) { amount = _exchangeRates().effectiveValue(synth, amount, sUSD); } _synthsUSD().issue(_feePool().FEE_ADDRESS(), amount); _feePool().recordFeePaid(amount); } } // ========== MODIFIERS ========== modifier rateIsValid() { _requireRateIsValid(); _; } function _requireRateIsValid() private { require(!_exchangeRates().rateIsInvalid(collateralKey), "Collateral rate is invalid"); } // ========== EVENTS ========== // Setters event MinCratioRatioUpdated(uint minCratio); event MinCollateralUpdated(uint minCollateral); event IssueFeeRateUpdated(uint issueFeeRate); event MaxLoansPerAccountUpdated(uint maxLoansPerAccount); event InteractionDelayUpdated(uint interactionDelay); event ManagerUpdated(address manager); event CanOpenLoansUpdated(bool canOpenLoans); // Loans event LoanCreated(address indexed account, uint id, uint amount, uint collateral, bytes32 currency, uint issuanceFee); event LoanClosed(address indexed account, uint id); event CollateralDeposited(address indexed account, uint id, uint amountDeposited, uint collateralAfter); event CollateralWithdrawn(address indexed account, uint id, uint amountWithdrawn, uint collateralAfter); event LoanRepaymentMade(address indexed account, address indexed repayer, uint id, uint amountRepaid, uint amountAfter); event LoanDrawnDown(address indexed account, uint id, uint amount); event LoanPartiallyLiquidated( address indexed account, uint id, address liquidator, uint amountLiquidated, uint collateralLiquidated ); event LoanClosedByLiquidation( address indexed account, uint id, address indexed liquidator, uint amountLiquidated, uint collateralLiquidated ); }
amount is the amount of synths we are liquidating
function collateralRedeemed(bytes32 currency, uint amount) public view returns (uint collateral) { uint liquidationPenalty = getLiquidationPenalty(); collateral = _exchangeRates().effectiveValue(currency, amount, collateralKey); collateral = collateral.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty)); }
1,763,586
./full_match/137/0xAc71AB6E64753173f9EEab006dabe8dfc3E1Ff71/sources/project_/flattened/WitnetPriceFeed/FlattenedWitnetPriceFeed.sol
Returns `true` if given price feed contract is currently serving updates to any known currency pair.
function supportsPriceFeed(IERC165 _pricefeed) public view virtual override returns (bool) { return __pairs[bytes4(__pricefeedId_[address(_pricefeed)])].pricefeed == _pricefeed; }
4,739,794
./full_match/421613/0x7dea2543217b98D3E313fe687C6d038C3Cd2E55A/sources/contracts/pachiSlot.sol
executePayout( _nonce, s_requests[_nonce].wager, s_requests[_nonce].betToken, s_requests[_nonce].from, _randomNumbers );
function callbackSpin( uint256 _nonce, uint256[] calldata _randomNumbers ) external { require( msg.sender == supraAddr, "only supra router can call this function" ); require(s_requests[_nonce].exists, "request not found"); require(!s_requests[_nonce].fulfilled, "request already fulfilled"); s_requests[_nonce].fulfilled = true; s_requests[_nonce].randomNumbers = _randomNumbers; waitingForResponse[s_requests[_nonce].from] = false; emit RequestFulfilled(_nonce, _randomNumbers); }
11,567,464
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'DENtoken' // // NAME : DENtoken // Symbol : DEN // Total supply: 25,000,000 // Decimals : 18 // ---------------------------------------------------------------------------- library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract ERC20Basic { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 { uint256 public totalSupply; bool public transfersEnabled; 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); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract DENtoken is StandardToken { string public constant name = "DENtoken"; string public constant symbol = "DEN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 25 * 10**6 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); function DENtoken() public { totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** * If the user sends 0 ether, he receives 500 * If he sends 0.01 ether, he receives 1000 * If he sends 0.1 ether he receives 10,000 * If he sends 1 ether, he receives 100,000 * If he sends 2 ether, he receives 200,000 * If he sends 5 ether, he receives 500,000 * If he sends 10 ether, he receives 1,000,000 */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 500 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 1000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 2000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 4000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 5000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 7000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 8000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 10000 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 20000 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 30000 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 40000 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 50000 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 60000 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 70000 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 80000 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 90000 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 100000 * (10**uint256(decimals)); } if( _weiAmount == 2 ether){ amountOfTokens = 200000 * (10**uint256(decimals)); } if( _weiAmount == 3 ether){ amountOfTokens = 300000 * (10**uint256(decimals)); } if( _weiAmount == 4 ether){ amountOfTokens = 400000 * (10**uint256(decimals)); } if( _weiAmount == 5 ether){ amountOfTokens = 500000 * (10**uint256(decimals)); } if( _weiAmount == 6 ether){ amountOfTokens = 600000 * (10**uint256(decimals)); } if( _weiAmount == 7 ether){ amountOfTokens = 700000 * (10**uint256(decimals)); } if( _weiAmount == 8 ether){ amountOfTokens = 800000 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 900000 * (10**uint256(decimals)); } if( _weiAmount == 10 ether){ amountOfTokens = 1000000 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
If the user sends 0 ether, he receives 500 If he sends 0.01 ether, he receives 1000 If he sends 0.1 ether he receives 10,000 If he sends 1 ether, he receives 100,000 If he sends 2 ether, he receives 200,000 If he sends 5 ether, he receives 500,000 If he sends 10 ether, he receives 1,000,000/
function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 500 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 1000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 2000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 4000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 5000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 7000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 8000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 10000 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 20000 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 30000 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 40000 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 50000 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 60000 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 70000 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 80000 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 90000 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 100000 * (10**uint256(decimals)); } if( _weiAmount == 2 ether){ amountOfTokens = 200000 * (10**uint256(decimals)); } if( _weiAmount == 3 ether){ amountOfTokens = 300000 * (10**uint256(decimals)); } if( _weiAmount == 4 ether){ amountOfTokens = 400000 * (10**uint256(decimals)); } if( _weiAmount == 5 ether){ amountOfTokens = 500000 * (10**uint256(decimals)); } if( _weiAmount == 6 ether){ amountOfTokens = 600000 * (10**uint256(decimals)); } if( _weiAmount == 7 ether){ amountOfTokens = 700000 * (10**uint256(decimals)); } if( _weiAmount == 8 ether){ amountOfTokens = 800000 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 900000 * (10**uint256(decimals)); } if( _weiAmount == 10 ether){ amountOfTokens = 1000000 * (10**uint256(decimals)); } return amountOfTokens; }
1,474,181
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/tokens/IERC20Mintable.sol"; import "./interfaces/tokens/IEXCToken.sol"; import "./interfaces/IMasterExcalibur.sol"; import "./interfaces/IMasterChef.sol"; contract MasterChef is Ownable, ReentrancyGuard, IMasterChef { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for IERC20Mintable; using SafeERC20 for IEXCToken; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided uint256 rewardDebt; // Reward debt. See explanation below /** * We do some fancy math here. Basically, any point in time, the amount of EXCs * entitled to a user but is pending to be distributed is: * * pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt * * Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: * 1. The pool's `accRrewardsPerShare` (and `lastRewardTime`) gets updated * 2. User receives the pending reward sent to his/her address * 3. User's `amount` gets updated * 4. User's `rewardDebt` gets updated */ } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract uint256 lpSupply; // Sum of LP staked on this pool uint256 lpSupplyWithMultiplier; // Sum of LP staked on this pool including the user's multiplier uint256 allocPoint; // How many allocation points assigned to this pool. EXC or GRAIL to distribute per second uint256 lastRewardTime; // Last time that EXC or GRAIL distribution occurs uint256 accRewardsPerShare; // Accumulated Rewards (EXC or GRAIL token) per share, times 1e18. See below uint256 depositFeeBP; // Deposit Fee bool isGrailRewards; // Are the rewards GRAIL token (if not, rewards are EXC) } IEXCToken internal immutable _excToken; // Address of the EXC token contract IERC20Mintable internal immutable _grailToken; // Address of the GRAIL token contract address public devAddress; // Dev address address public feeAddress; // Deposit Fee address mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Info of each user that stakes LP tokens PoolInfo[] public poolInfo; // Info of each pool uint256 public totalAllocPoint = 0; // Total allocation points. Must be the sum of all allocation points in all pools uint256 public immutable startTime; // The time at which mining starts uint256 public constant MAX_DEPOSIT_FEE_BP = 400; // 4% uint256 public constant INITIAL_EMISSION_RATE = 1 ether; // Initial emission rate : EXC+GRAIL per second uint256 public constant MINIMUM_EMISSION_RATE = 0.1 ether; uint256 public rewardsPerSecond; // Token rewards created per second constructor( IEXCToken excToken_, IERC20Mintable grailToken_, uint256 startTime_, address devAddress_, address feeAddress_ ) { require(devAddress_ != address(0), "constructor: devAddress init with zero address"); require(feeAddress_ != address(0), "constructor: feeAddress init with zero address"); _excToken = excToken_; _grailToken = grailToken_; startTime = startTime_; rewardsPerSecond = INITIAL_EMISSION_RATE; devAddress = devAddress_; feeAddress = feeAddress_; // staking pool poolInfo.push( PoolInfo({ lpToken: excToken_, lpSupply: 0, lpSupplyWithMultiplier: 0, allocPoint: 800, lastRewardTime: startTime_, accRewardsPerShare: 0, depositFeeBP: 0, isGrailRewards: false }) ); totalAllocPoint = 800; } /********************************************/ /****************** EVENTS ******************/ /********************************************/ event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmissionRateUpdated(uint256 previousEmissionRate, uint256 newEmissionRate); event PoolAdded(uint256 indexed pid, uint256 allocPoint, address lpToken, uint256 depositFeeBP, bool isGrailRewards); event PoolConfigUpdated(uint256 indexed pid, uint256 allocPoint, address lpToken, uint256 depositFeeBP); event PoolUpdated(uint256 indexed pid, uint256 lastRewardTime, uint256 accRewardsPerShare); event FeeAddressUpdated(address previousAddress, address newAddress); event DevAddressUpdated(address previousAddress, address newAddress); /***********************************************/ /****************** MODIFIERS ******************/ /***********************************************/ /* * @dev Check if a pid exists */ modifier validatePool(uint256 pid) { require(pid < poolInfo.length, "validatePool: pool exists?"); _; } /**************************************************/ /****************** PUBLIC VIEWS ******************/ /**************************************************/ function excToken() external view override returns (address) { return address(_excToken); } function grailToken() external view override returns (address) { return address(_grailToken); } /** * @dev Returns the number of available pools */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @dev Returns user data for a given pool */ function getUserInfo(uint256 pid, address userAddress) external view override returns (uint256 amount, uint256 rewardDebt) { UserInfo storage user = userInfo[pid][userAddress]; return (user.amount, user.rewardDebt); } /** * @dev Returns data of a given pool */ function getPoolInfo(uint256 pid) external view override returns ( address lpToken, uint256 allocPoint, uint256 lastRewardTime, uint256 accRewardsPerShare, uint256 depositFeeBP, bool isGrailRewards, uint256 lpSupply, uint256 lpSupplyWithMultiplier ) { PoolInfo storage pool = poolInfo[pid]; return ( address(pool.lpToken), pool.allocPoint, pool.lastRewardTime, pool.accRewardsPerShare, pool.depositFeeBP, pool.isGrailRewards, pool.lpSupply, pool.lpSupplyWithMultiplier ); } /** * @dev Returns a given user pending rewards for a given pool */ function pendingRewards(uint256 pid, address userAddress) external view returns (uint256 pending) { uint256 accRewardsPerShare = _getCurrentAccRewardsPerShare(pid); UserInfo storage user = userInfo[pid][userAddress]; pending = user.amount.mul(accRewardsPerShare).div(1e18).sub(user.rewardDebt); return pending; } /****************************************************************/ /****************** EXTERNAL PUBLIC FUNCTIONS ******************/ /****************************************************************/ /** * @dev Updates rewards states of the given pool to be up-to-date */ function updatePool(uint256 pid) external nonReentrant validatePool(pid) { _updatePool(pid); } /** * @dev Updates rewards states for all pools * * Be careful of gas spending */ function massUpdatePools() external nonReentrant { _massUpdatePools(); } /** * @dev Harvests user's pending rewards on a given pool */ function harvest(uint256 pid) external override nonReentrant validatePool(pid) { address userAddress = msg.sender; PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][userAddress]; _updatePool(pid); _harvest(pid, pool, user, userAddress); user.rewardDebt = user.amount.mul(pool.accRewardsPerShare).div(1e18); } /** * @dev Deposits LP tokens on a given pool for rewards allocation */ function deposit(uint256 pid, uint256 amount) external override nonReentrant validatePool(pid) { address userAddress = msg.sender; PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][userAddress]; _updatePool(pid); _harvest(pid, pool, user, userAddress); if (amount > 0) { // handle tokens with auto burn uint256 previousBalance = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(userAddress, address(this), amount); amount = pool.lpToken.balanceOf(address(this)).sub(previousBalance); // check if depositFee is enabled if (pool.depositFeeBP > 0) { uint256 depositFee = amount.mul(pool.depositFeeBP).div(10000); amount = amount.sub(depositFee); pool.lpToken.safeTransfer(feeAddress, depositFee); } user.amount = user.amount.add(amount); pool.lpSupply = pool.lpSupply.add(amount); pool.lpSupplyWithMultiplier = pool.lpSupplyWithMultiplier.add(amount); } user.rewardDebt = user.amount.mul(pool.accRewardsPerShare).div(1e18); emit Deposit(userAddress, pid, amount); } /** * @dev Withdraw LP tokens from a given pool */ function withdraw(uint256 pid, uint256 amount) external override nonReentrant validatePool(pid) { address userAddress = msg.sender; PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][userAddress]; require(user.amount >= amount, "withdraw: invalid amount"); _updatePool(pid); _harvest(pid, pool, user, userAddress); if (amount > 0) { user.amount = user.amount.sub(amount); pool.lpSupply = pool.lpSupply.sub(amount); pool.lpSupplyWithMultiplier = pool.lpSupplyWithMultiplier.sub(amount); pool.lpToken.safeTransfer(userAddress, amount); } user.rewardDebt = user.amount.mul(pool.accRewardsPerShare).div(1e18); emit Withdraw(userAddress, pid, amount); } /** * @dev Withdraw without caring about rewards, EMERGENCY ONLY */ function emergencyWithdraw(uint256 pid) external validatePool(pid) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; pool.lpSupply = pool.lpSupply.sub(user.amount); pool.lpSupplyWithMultiplier = pool.lpSupplyWithMultiplier.sub(user.amount); user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, pid, amount); pool.lpToken.safeTransfer(msg.sender, amount); } /*****************************************************************/ /****************** EXTERNAL OWNABLE FUNCTIONS ******************/ /*****************************************************************/ /** * @dev Updates dev address * * Must only be called by devAddress */ function setDevAddress(address newDevAddress) external { require(msg.sender == devAddress, "caller is not devAddress"); require(newDevAddress != address(0), "zero address"); emit DevAddressUpdated(devAddress, newDevAddress); devAddress = newDevAddress; } /** * @dev Updates fee address * * Must only be called by the owner */ function setFeeAddress(address newFeeAddress) external onlyOwner { require(newFeeAddress != address(0), "zero address"); emit FeeAddressUpdated(feeAddress, newFeeAddress); feeAddress = newFeeAddress; } /** * @dev Updates the emission rate * param withUpdate should be set to true every time it's possible * * Must only be called by the owner */ function updateEmissionRate(uint256 newEmissionRate, bool withUpdate) external onlyOwner { require(newEmissionRate >= MINIMUM_EMISSION_RATE, "rewardsPerSecond mustn't exceed the minimum"); require(newEmissionRate <= INITIAL_EMISSION_RATE, "rewardsPerSecond mustn't exceed the maximum"); if(withUpdate) _massUpdatePools(); emit EmissionRateUpdated(rewardsPerSecond, newEmissionRate); rewardsPerSecond = newEmissionRate; } /** * @dev Adds a new pool * param withUpdate should be set to true every time it's possible * * Must only be called by the owner */ function add( uint256 allocPoint, IERC20 lpToken, uint256 depositFeeBP, bool isGrailRewards, bool withUpdate ) external onlyOwner { require(depositFeeBP <= MAX_DEPOSIT_FEE_BP, "add: invalid deposit fee basis points"); uint256 currentBlockTimestamp = _currentBlockTimestamp(); if (withUpdate && allocPoint > 0) { // Updates all pools if new pool allocPoint > 0 _massUpdatePools(); } uint256 lastRewardTime = currentBlockTimestamp > startTime ? currentBlockTimestamp : startTime; totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push( PoolInfo({ lpToken: lpToken, lpSupply: 0, lpSupplyWithMultiplier: 0, allocPoint: allocPoint, lastRewardTime: lastRewardTime, accRewardsPerShare: 0, depositFeeBP: depositFeeBP, isGrailRewards: isGrailRewards }) ); emit PoolAdded(poolInfo.length.sub(1), allocPoint, address(lpToken), depositFeeBP, isGrailRewards); } /** * @dev Updates configuration on existing pool * param withUpdate should be set to true every time it's possible * * Must only be called by the owner */ function set( uint256 pid, uint256 allocPoint, uint256 depositFeeBP, bool withUpdate ) external onlyOwner { require(depositFeeBP <= MAX_DEPOSIT_FEE_BP, "set: invalid deposit fee basis points"); PoolInfo storage pool = poolInfo[pid]; uint256 prevAllocPoint = pool.allocPoint; if (withUpdate && allocPoint != prevAllocPoint) { // Updates each existent pool if new allocPoints differ from the previously ones _massUpdatePools(); } pool.allocPoint = allocPoint; pool.depositFeeBP = depositFeeBP; if (prevAllocPoint != allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(allocPoint); } emit PoolConfigUpdated(pid, allocPoint, address(pool.lpToken), depositFeeBP); } /********************************************************/ /****************** INTERNAL FUNCTIONS ******************/ /********************************************************/ /** * @dev Returns the accRewardsPerShare adjusted for current block of a given pool */ function _getCurrentAccRewardsPerShare(uint256 pid) internal view returns (uint256) { uint256 currentBlockTimestamp = _currentBlockTimestamp(); PoolInfo storage pool = poolInfo[pid]; uint256 accRewardsPerShare = pool.accRewardsPerShare; // check if pool is active and not already up-to-date if (currentBlockTimestamp > pool.lastRewardTime && pool.lpSupplyWithMultiplier > 0) { uint256 nbSeconds = currentBlockTimestamp.sub(pool.lastRewardTime); uint256 tokensReward = nbSeconds.mul(rewardsPerSecond).mul(pool.allocPoint).mul(1e18).div(totalAllocPoint); return accRewardsPerShare.add(tokensReward.div(pool.lpSupplyWithMultiplier)); } return accRewardsPerShare; } /** * @dev Harvests the pending rewards for a given pool and user * Does not update user.rewardDebt ! * Functions calling this must update rewardDebt themselves */ function _harvest( uint256 pid, PoolInfo storage pool, UserInfo storage user, address userAddress ) internal { if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRewardsPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { if (pool.isGrailRewards) { _safeRewardsTransfer(userAddress, pending, _grailToken); } else { _safeRewardsTransfer(userAddress, pending, _excToken); } emit Harvest(userAddress, pid, pending); } } } /** * @dev Safe token transfer function, in case rounding error causes pool to not have enough tokens */ function _safeRewardsTransfer( address to, uint256 amount, IERC20Mintable tokenReward ) internal { uint256 tokenRewardBalance = tokenReward.balanceOf(address(this)); bool transferSuccess = false; if (amount > tokenRewardBalance) { transferSuccess = tokenReward.transfer(to, tokenRewardBalance); } else { transferSuccess = tokenReward.transfer(to, amount); } require(transferSuccess, "safeRewardTransfer: Transfer failed"); } /** * @dev Updates rewards states of the given pool to be up-to-date */ function _updatePool(uint256 pid) internal { uint256 currentBlockTimestamp = _currentBlockTimestamp(); PoolInfo storage pool = poolInfo[pid]; if (currentBlockTimestamp <= pool.lastRewardTime) { return; } if (pool.lpSupplyWithMultiplier == 0) { pool.lastRewardTime = currentBlockTimestamp; return; } uint256 nbSeconds = currentBlockTimestamp.sub(pool.lastRewardTime); uint256 tokensReward = nbSeconds.mul(rewardsPerSecond).mul(pool.allocPoint).div(totalAllocPoint); pool.accRewardsPerShare = pool.accRewardsPerShare.add(tokensReward.mul(1e18).div(pool.lpSupplyWithMultiplier)); pool.lastRewardTime = currentBlockTimestamp; _excToken.mint(devAddress, tokensReward.div(10)); if (pool.isGrailRewards) { _grailToken.mint(address(this), tokensReward); } else { _excToken.mint(address(this), tokensReward); } emit PoolUpdated(pid, pool.lastRewardTime, pool.accRewardsPerShare); } /** * @dev Updates rewards states for all pools * * Be careful of gas spending */ function _massUpdatePools() internal { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { _updatePool(pid); } } /** * @dev Utility function to get the current block timestamp */ function _currentBlockTimestamp() internal view virtual returns (uint256) { return block.timestamp; } }
Updates rewards states of the given pool to be up-to-date/
function updatePool(uint256 pid) external nonReentrant validatePool(pid) { _updatePool(pid); }
12,713,213
pragma solidity ^0.4.25; /** * * World War Goo - Competitive Idle Game * * https://ethergoo.io * */ interface ERC721 { function totalSupply() external view returns (uint256 tokens); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function exists(uint256 tokenId) external view returns (bool tokenExists); function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address approvee); function transferFrom(address from, address to, uint256 tokenId) external; function tokensOf(address owner) external view returns (uint256[] tokens); //function tokenByIndex(uint256 index) external view returns (uint256 token); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); } interface ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) external; } contract Clans is ERC721, ApproveAndCallFallBack { using SafeMath for uint256; GooToken constant goo = GooToken(0xdf0960778c6e6597f197ed9a25f12f5d971da86c); Army constant army = Army(0x98278eb74b388efd4d6fc81dd3f95b642ce53f2b); WWGClanCoupons constant clanCoupons = WWGClanCoupons(0xe9fe4e530ebae235877289bd978f207ae0c8bb25); // For minting clans to initial owners (prelaunch buyers) string public constant name = "Goo Clan"; string public constant symbol = "GOOCLAN"; uint224 numClans; address owner; // Minor management // ERC721 stuff mapping (uint256 => address) public tokenOwner; mapping (uint256 => address) public tokenApprovals; mapping (address => uint256[]) public ownedTokens; mapping(uint256 => uint256) public ownedTokensIndex; mapping(address => UserClan) public userClan; mapping(uint256 => uint224) public clanFee; mapping(uint256 => uint224) public leaderFee; mapping(uint256 => uint256) public clanMembers; mapping(uint256 => mapping(uint256 => uint224)) public clanUpgradesOwned; mapping(uint256 => uint256) public clanGoo; mapping(uint256 => address) public clanToken; // i.e. BNB mapping(uint256 => uint256) public baseTokenDenomination; // base value for token gains i.e. 0.000001 BNB mapping(uint256 => uint256) public clanTotalArmyPower; mapping(uint256 => uint224) public referalFee; // If invited to a clan how much % of player's divs go to referer mapping(address => mapping(uint256 => address)) public clanReferer; // Address of who invited player to each clan mapping(uint256 => Upgrade) public upgradeList; mapping(address => bool) operator; struct UserClan { uint224 clanId; uint32 clanJoinTime; } struct Upgrade { uint256 upgradeId; uint224 gooCost; uint224 upgradeGain; uint256 upgradeClass; uint256 prerequisiteUpgrade; } // Events event JoinedClan(uint256 clanId, address player, address referer); event LeftClan(uint256 clanId, address player); constructor() public { owner = msg.sender; } function setOperator(address gameContract, bool isOperator) external { require(msg.sender == owner); operator[gameContract] = isOperator; } function totalSupply() external view returns (uint256) { return numClans; } function balanceOf(address player) public view returns (uint256) { return ownedTokens[player].length; } function ownerOf(uint256 clanId) external view returns (address) { return tokenOwner[clanId]; } function exists(uint256 clanId) public view returns (bool) { return tokenOwner[clanId] != address(0); } function approve(address to, uint256 clanId) external { require(tokenOwner[clanId] == msg.sender); tokenApprovals[clanId] = to; emit Approval(msg.sender, to, clanId); } function getApproved(uint256 clanId) external view returns (address) { return tokenApprovals[clanId]; } function tokensOf(address player) external view returns (uint256[] tokens) { return ownedTokens[player]; } function transferFrom(address from, address to, uint256 tokenId) public { require(tokenApprovals[tokenId] == msg.sender || tokenOwner[tokenId] == msg.sender); joinClanPlayer(to, uint224(tokenId), 0); // uint224 won't overflow due to tokenOwner check in removeTokenFrom() removeTokenFrom(from, tokenId); addTokenTo(to, tokenId); delete tokenApprovals[tokenId]; // Clear approval emit Transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public { transferFrom(from, to, tokenId); checkERC721Recieved(from, to, tokenId, data); } function checkERC721Recieved(address from, address to, uint256 tokenId, bytes memory data) internal { uint256 size; assembly { size := extcodesize(to) } if (size > 0) { // Recipient is contract so must confirm recipt bytes4 successfullyRecieved = ERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data); require(successfullyRecieved == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))); } } function removeTokenFrom(address from, uint256 tokenId) internal { require(tokenOwner[tokenId] == from); tokenOwner[tokenId] = address(0); uint256 tokenIndex = ownedTokensIndex[tokenId]; uint256 lastTokenIndex = ownedTokens[from].length.sub(1); uint256 lastToken = ownedTokens[from][lastTokenIndex]; ownedTokens[from][tokenIndex] = lastToken; ownedTokens[from][lastTokenIndex] = 0; ownedTokens[from].length--; ownedTokensIndex[tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } function addTokenTo(address to, uint256 tokenId) internal { require(ownedTokens[to].length == 0); // Can't own multiple clans tokenOwner[tokenId] = to; ownedTokensIndex[tokenId] = ownedTokens[to].length; ownedTokens[to].push(tokenId); } function updateClanFees(uint224 newClanFee, uint224 newLeaderFee, uint224 newReferalFee, uint256 clanId) external { require(msg.sender == tokenOwner[clanId]); require(newClanFee <= 25); // 25% max fee require(newReferalFee <= 10); // 10% max refs require(newLeaderFee <= newClanFee); // Clan gets fair cut clanFee[clanId] = newClanFee; leaderFee[clanId] = newLeaderFee; referalFee[clanId] = newReferalFee; } function getPlayerFees(address player) external view returns (uint224 clansFee, uint224 leadersFee, address leader, uint224 referalsFee, address referer) { uint256 usersClan = userClan[player].clanId; clansFee = clanFee[usersClan]; leadersFee = leaderFee[usersClan]; leader = tokenOwner[usersClan]; referalsFee = referalFee[usersClan]; referer = clanReferer[player][usersClan]; } function getPlayersClanUpgrade(address player, uint256 upgradeClass) external view returns (uint224 upgradeGain) { upgradeGain = upgradeList[clanUpgradesOwned[userClan[player].clanId][upgradeClass]].upgradeGain; } function getClanUpgrade(uint256 clanId, uint256 upgradeClass) external view returns (uint224 upgradeGain) { upgradeGain = upgradeList[clanUpgradesOwned[clanId][upgradeClass]].upgradeGain; } // Convienence function function getClanDetailsForAttack(address player, address target) external view returns (uint256 clanId, uint256 targetClanId, uint224 playerLootingBonus) { clanId = userClan[player].clanId; targetClanId = userClan[target].clanId; playerLootingBonus = upgradeList[clanUpgradesOwned[clanId][3]].upgradeGain; // class 3 = looting bonus } function joinClan(uint224 clanId, address referer) external { require(exists(clanId)); joinClanPlayer(msg.sender, clanId, referer); } // Allows smarter invites/referals in future function joinClanFromInvite(address player, uint224 clanId, address referer) external { require(operator[msg.sender]); joinClanPlayer(player, clanId, referer); } function joinClanPlayer(address player, uint224 clanId, address referer) internal { require(ownedTokens[player].length == 0); // Owners can't join (uint80 attack, uint80 defense,) = army.getArmyPower(player); // Leave old clan UserClan memory existingClan = userClan[player]; if (existingClan.clanId > 0) { clanMembers[existingClan.clanId]--; clanTotalArmyPower[existingClan.clanId] -= (attack + defense); emit LeftClan(existingClan.clanId, player); } if (referer != address(0) && referer != player) { require(userClan[referer].clanId == clanId); clanReferer[player][clanId] = referer; } existingClan.clanId = clanId; existingClan.clanJoinTime = uint32(now); clanMembers[clanId]++; clanTotalArmyPower[clanId] += (attack + defense); userClan[player] = existingClan; emit JoinedClan(clanId, player, referer); } function leaveClan() external { require(ownedTokens[msg.sender].length == 0); // Owners can't leave UserClan memory usersClan = userClan[msg.sender]; require(usersClan.clanId > 0); (uint80 attack, uint80 defense,) = army.getArmyPower(msg.sender); clanTotalArmyPower[usersClan.clanId] -= (attack + defense); clanMembers[usersClan.clanId]--; delete userClan[msg.sender]; emit LeftClan(usersClan.clanId, msg.sender); // Cannot leave if player has unclaimed divs (edge case for clan fee abuse) require(attack + defense == 0 || army.lastWarFundClaim(msg.sender) == army.getSnapshotDay()); require(usersClan.clanJoinTime + 24 hours < now); } function mintClan(address recipient, uint224 referalPercent, address clanTokenAddress, uint256 baseTokenReward) external { require(operator[msg.sender]); require(ERC20(clanTokenAddress).totalSupply() > 0); numClans++; uint224 clanId = numClans; // Starts from clanId 1 // Add recipient to clan joinClanPlayer(recipient, clanId, 0); require(tokenOwner[clanId] == address(0)); addTokenTo(recipient, clanId); emit Transfer(address(0), recipient, clanId); // Store clan token clanToken[clanId] = clanTokenAddress; baseTokenDenomination[clanId] = baseTokenReward; referalFee[clanId] = referalPercent; // Burn clan coupons from owner (prelaunch event) if (clanCoupons.totalSupply() > 0) { clanCoupons.burnCoupon(recipient, clanId); } } function addUpgrade(uint256 id, uint224 gooCost, uint224 upgradeGain, uint256 upgradeClass, uint256 prereq) external { require(operator[msg.sender]); upgradeList[id] = Upgrade(id, gooCost, upgradeGain, upgradeClass, prereq); } // Incase an existing token becomes invalid (i.e. migrates away) function updateClanToken(uint256 clanId, address newClanToken, bool shouldRetrieveOldTokens) external { require(msg.sender == owner); require(ERC20(newClanToken).totalSupply() > 0); if (shouldRetrieveOldTokens) { ERC20(clanToken[clanId]).transferFrom(this, owner, ERC20(clanToken[clanId]).balanceOf(this)); } clanToken[clanId] = newClanToken; } // Incase need to tweak/balance attacking rewards (i.e. token moons so not viable to restock at current level) function updateClanTokenGain(uint256 clanId, uint256 baseTokenReward) external { require(msg.sender == owner); baseTokenDenomination[clanId] = baseTokenReward; } // Clan member goo deposits function receiveApproval(address player, uint256 amount, address, bytes) external { uint256 clanId = userClan[player].clanId; require(exists(clanId)); require(msg.sender == address(goo)); ERC20(msg.sender).transferFrom(player, address(0), amount); clanGoo[clanId] += amount; } function buyUpgrade(uint224 upgradeId) external { uint256 clanId = userClan[msg.sender].clanId; require(msg.sender == tokenOwner[clanId]); Upgrade memory upgrade = upgradeList[upgradeId]; require (upgrade.upgradeId > 0); // Valid upgrade uint256 upgradeClass = upgrade.upgradeClass; uint256 latestOwned = clanUpgradesOwned[clanId][upgradeClass]; require(latestOwned < upgradeId); // Haven't already purchased require(latestOwned >= upgrade.prerequisiteUpgrade); // Own prequisite // Clan discount uint224 upgradeDiscount = clanUpgradesOwned[clanId][0]; // class 0 = upgrade discount uint224 reducedUpgradeCost = upgrade.gooCost - ((upgrade.gooCost * upgradeDiscount) / 100); clanGoo[clanId] = clanGoo[clanId].sub(reducedUpgradeCost); army.depositSpentGoo(reducedUpgradeCost); // Transfer to goo bankroll clanUpgradesOwned[clanId][upgradeClass] = upgradeId; } // Goo from divs etc. function depositGoo(uint256 amount, uint256 clanId) external { require(operator[msg.sender]); require(exists(clanId)); clanGoo[clanId] += amount; } function increaseClanPower(address player, uint256 amount) external { require(operator[msg.sender]); uint256 clanId = userClan[player].clanId; if (clanId > 0) { clanTotalArmyPower[clanId] += amount; } } function decreaseClanPower(address player, uint256 amount) external { require(operator[msg.sender]); uint256 clanId = userClan[player].clanId; if (clanId > 0) { clanTotalArmyPower[clanId] -= amount; } } function stealGoo(address attacker, uint256 playerClanId, uint256 enemyClanId, uint80 lootingPower) external returns(uint256) { require(operator[msg.sender]); uint224 enemyGoo = uint224(clanGoo[enemyClanId]); uint224 enemyGooStolen = (lootingPower > enemyGoo) ? enemyGoo : lootingPower; clanGoo[enemyClanId] = clanGoo[enemyClanId].sub(enemyGooStolen); uint224 clansShare = (enemyGooStolen * clanFee[playerClanId]) / 100; uint224 referersFee = referalFee[playerClanId]; address referer = clanReferer[attacker][playerClanId]; if (clansShare > 0 || (referersFee > 0 && referer != address(0))) { uint224 leaderShare = (enemyGooStolen * leaderFee[playerClanId]) / 100; uint224 refsShare; if (referer != address(0)) { refsShare = (enemyGooStolen * referersFee) / 100; goo.mintGoo(refsShare, referer); } clanGoo[playerClanId] += clansShare; goo.mintGoo(leaderShare, tokenOwner[playerClanId]); goo.mintGoo(enemyGooStolen - (clansShare + leaderShare + refsShare), attacker); } else { goo.mintGoo(enemyGooStolen, attacker); } return enemyGooStolen; } function rewardTokens(address attacker, uint256 playerClanId, uint80 lootingPower) external returns(uint256) { require(operator[msg.sender]); uint256 amount = baseTokenDenomination[playerClanId] * lootingPower; ERC20(clanToken[playerClanId]).transfer(attacker, amount); return amount; } // Daily clan dividends function mintGoo(address player, uint256 amount) external { require(operator[msg.sender]); clanGoo[userClan[player].clanId] += amount; } } contract ERC20 { function transferFrom(address from, address to, uint tokens) external returns (bool success); function transfer(address to, uint tokens) external returns (bool success); function totalSupply() external constant returns (uint); function balanceOf(address tokenOwner) external constant returns (uint balance); } contract GooToken { function mintGoo(uint224 amount, address player) external; function updatePlayersGooFromPurchase(address player, uint224 purchaseCost) external; } contract Army { mapping(address => uint256) public lastWarFundClaim; // Days (snapshot number) function depositSpentGoo(uint224 amount) external; function getArmyPower(address player) external view returns (uint80, uint80, uint80); function getSnapshotDay() external view returns (uint256 snapshot); } contract WWGClanCoupons { function totalSupply() external view returns (uint256); function burnCoupon(address clanOwner, uint256 tokenId) external; } contract ERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes data) external returns(bytes4); } 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; } }
Clan member goo deposits
function receiveApproval(address player, uint256 amount, address, bytes) external { uint256 clanId = userClan[player].clanId; require(exists(clanId)); require(msg.sender == address(goo)); ERC20(msg.sender).transferFrom(player, address(0), amount); clanGoo[clanId] += amount; }
5,358,429
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 fromBlock; uint256 votes; } contract ProjectToken is IERC20, ReentrancyGuard { using SafeMath for uint256; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); uint256 public override totalSupply; string public symbol; uint8 public decimals; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; constructor(string memory _symbol) public { symbol = _symbol; decimals = 18; } function getChainId() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } return chainId; } function balanceOf(address account) public view override returns (uint256 free) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address account_owner, address spender) public view virtual override returns (uint256) { return _allowances[account_owner][spender]; } function approve(address spender, uint256 amount) public virtual override nonReentrant returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual nonReentrant returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual nonReentrant returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == block.number ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( block.number, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public nonReentrant { return _delegate(msg.sender, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "StakingToken: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint256 delegatorBalance = _balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual { // if (from == address(0)) { // // When minting tokens // uint256 newSupply = totalSupply().add(amount); // require( // newSupply <= _softcap && newSupply <= _cap, // "ERC20Capped: cap exceeded" // ); // } } function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual { _moveDelegates(from, to, amount); } function _approve( address account_owner, address spender, uint256 amount ) internal virtual { require( account_owner != address(0), "ERC20: approve from the zero address" ); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[account_owner][spender] = amount; emit Approval(account_owner, spender, 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); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); totalSupply = totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } }
Delegate votes from `msg.sender` to `delegatee` delegatee The address to delegate votes to/
function delegate(address delegatee) public nonReentrant { return _delegate(msg.sender, delegatee); }
1,758,304
./partial_match/1/0x4c7fbeEC0412976f59D83eAdee34BFE7ca2540DC/sources/Pyromaniac.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("PyroManiac", "PYRO") { 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 = 15; uint256 _buyLiquidityFee = 5; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 40; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; maxWallet = 20_000_000 * 1e18; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; deployerWallet = address(0x59db2Bd6AC5cFAC7B6d89127a36F5492ab0656A2); lpLocker = address(0x663A5C229c09b049E36dCc11a9B0d4a8Eb9db214); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(marketingWallet, true); excludeFromFees(lpLocker, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(deployerWallet, true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(lpLocker, true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,032,323
./partial_match/42/0x65242F75e6cCBF973b15d483dD5F555d13955A1e/sources/TinlakeManager.sol
draw & wipe call daiJoin.exit/join immediately
function draw(uint wad) public ownerOnly note { require(safe && live); (,uint rate, , , ) = vat.ilks(ilk); uint dart = divup(mul(ONE, wad), rate); require(int(dart) >= 0, "TinlakeManager/overflow"); vat.frob(ilk, address(this), address(this), address(this), 0, int(dart)); daiJoin.exit(msg.sender, wad); }
3,383,960
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "../Euler.sol"; import "../Storage.sol"; import "../modules/EToken.sol"; import "../modules/Markets.sol"; import "../BaseIRMLinearKink.sol"; import "../vendor/RPow.sol"; interface IExec { function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice); function getPrice(address underlying) external view returns (uint twap, uint twapPeriod); function detailedLiquidity(address account) external view returns (IRiskManager.AssetLiquidity[] memory assets); function liquidity(address account) external view returns (IRiskManager.LiquidityStatus memory status); } contract EulerGeneralView is Constants { bytes32 immutable public moduleGitCommit; constructor(bytes32 moduleGitCommit_) { moduleGitCommit = moduleGitCommit_; } // Query struct Query { address eulerContract; address account; address[] markets; } // Response struct ResponseMarket { // Universal address underlying; string name; string symbol; uint8 decimals; address eTokenAddr; address dTokenAddr; address pTokenAddr; Storage.AssetConfig config; uint poolSize; uint totalBalances; uint totalBorrows; uint reserveBalance; uint32 reserveFee; uint borrowAPY; uint supplyAPY; // Pricing uint twap; uint twapPeriod; uint currPrice; uint16 pricingType; uint32 pricingParameters; address pricingForwarded; // Account specific uint underlyingBalance; uint eulerAllowance; uint eTokenBalance; uint eTokenBalanceUnderlying; uint dTokenBalance; IRiskManager.LiquidityStatus liquidityStatus; } struct Response { uint timestamp; uint blockNumber; ResponseMarket[] markets; address[] enteredMarkets; } // Implementation function doQueryBatch(Query[] memory qs) external view returns (Response[] memory r) { r = new Response[](qs.length); for (uint i = 0; i < qs.length; ++i) { r[i] = doQuery(qs[i]); } } function doQuery(Query memory q) public view returns (Response memory r) { r.timestamp = block.timestamp; r.blockNumber = block.number; Euler eulerProxy = Euler(q.eulerContract); Markets marketsProxy = Markets(eulerProxy.moduleIdToProxy(MODULEID__MARKETS)); IExec execProxy = IExec(eulerProxy.moduleIdToProxy(MODULEID__EXEC)); IRiskManager.AssetLiquidity[] memory liqs; if (q.account != address(0)) { liqs = execProxy.detailedLiquidity(q.account); } r.markets = new ResponseMarket[](liqs.length + q.markets.length); for (uint i = 0; i < liqs.length; ++i) { ResponseMarket memory m = r.markets[i]; m.underlying = liqs[i].underlying; m.liquidityStatus = liqs[i].status; populateResponseMarket(q, m, marketsProxy, execProxy); } for (uint j = liqs.length; j < liqs.length + q.markets.length; ++j) { uint i = j - liqs.length; ResponseMarket memory m = r.markets[j]; m.underlying = q.markets[i]; populateResponseMarket(q, m, marketsProxy, execProxy); } if (q.account != address(0)) { r.enteredMarkets = marketsProxy.getEnteredMarkets(q.account); } } function populateResponseMarket(Query memory q, ResponseMarket memory m, Markets marketsProxy, IExec execProxy) private view { m.name = getStringOrBytes32(m.underlying, IERC20.name.selector); m.symbol = getStringOrBytes32(m.underlying, IERC20.symbol.selector); m.decimals = IERC20(m.underlying).decimals(); m.eTokenAddr = marketsProxy.underlyingToEToken(m.underlying); if (m.eTokenAddr == address(0)) return; // not activated m.dTokenAddr = marketsProxy.eTokenToDToken(m.eTokenAddr); m.pTokenAddr = marketsProxy.underlyingToPToken(m.underlying); { Storage.AssetConfig memory c = marketsProxy.underlyingToAssetConfig(m.underlying); m.config = c; } m.poolSize = IERC20(m.underlying).balanceOf(q.eulerContract); m.totalBalances = EToken(m.eTokenAddr).totalSupplyUnderlying(); m.totalBorrows = IERC20(m.dTokenAddr).totalSupply(); m.reserveBalance = EToken(m.eTokenAddr).reserveBalanceUnderlying(); m.reserveFee = marketsProxy.reserveFee(m.underlying); { uint borrowSPY = uint(int(marketsProxy.interestRate(m.underlying))); (m.borrowAPY, m.supplyAPY) = computeAPYs(borrowSPY, m.totalBorrows, m.totalBalances, m.reserveFee); } (m.twap, m.twapPeriod, m.currPrice) = execProxy.getPriceFull(m.underlying); (m.pricingType, m.pricingParameters, m.pricingForwarded) = marketsProxy.getPricingConfig(m.underlying); if (q.account == address(0)) return; m.underlyingBalance = IERC20(m.underlying).balanceOf(q.account); m.eTokenBalance = IERC20(m.eTokenAddr).balanceOf(q.account); m.eTokenBalanceUnderlying = EToken(m.eTokenAddr).balanceOfUnderlying(q.account); m.dTokenBalance = IERC20(m.dTokenAddr).balanceOf(q.account); m.eulerAllowance = IERC20(m.underlying).allowance(q.account, q.eulerContract); } function computeAPYs(uint borrowSPY, uint totalBorrows, uint totalBalancesUnderlying, uint32 reserveFee) public pure returns (uint borrowAPY, uint supplyAPY) { borrowAPY = RPow.rpow(borrowSPY + 1e27, SECONDS_PER_YEAR, 10**27) - 1e27; uint supplySPY = totalBalancesUnderlying == 0 ? 0 : borrowSPY * totalBorrows / totalBalancesUnderlying; supplySPY = supplySPY * (RESERVE_FEE_SCALE - reserveFee) / RESERVE_FEE_SCALE; supplyAPY = RPow.rpow(supplySPY + 1e27, SECONDS_PER_YEAR, 10**27) - 1e27; } // Interest rate model queries struct QueryIRM { address eulerContract; address underlying; } struct ResponseIRM { uint kink; uint baseAPY; uint kinkAPY; uint maxAPY; uint baseSupplyAPY; uint kinkSupplyAPY; uint maxSupplyAPY; } function doQueryIRM(QueryIRM memory q) external view returns (ResponseIRM memory r) { Euler eulerProxy = Euler(q.eulerContract); Markets marketsProxy = Markets(eulerProxy.moduleIdToProxy(MODULEID__MARKETS)); uint moduleId = marketsProxy.interestRateModel(q.underlying); address moduleImpl = eulerProxy.moduleIdToImplementation(moduleId); BaseIRMLinearKink irm = BaseIRMLinearKink(moduleImpl); uint kink = r.kink = irm.kink(); uint32 reserveFee = marketsProxy.reserveFee(q.underlying); uint baseSPY = irm.baseRate(); uint kinkSPY = baseSPY + (kink * irm.slope1()); uint maxSPY = kinkSPY + ((type(uint32).max - kink) * irm.slope2()); (r.baseAPY, r.baseSupplyAPY) = computeAPYs(baseSPY, 0, type(uint32).max, reserveFee); (r.kinkAPY, r.kinkSupplyAPY) = computeAPYs(kinkSPY, kink, type(uint32).max, reserveFee); (r.maxAPY, r.maxSupplyAPY) = computeAPYs(maxSPY, type(uint32).max, type(uint32).max, reserveFee); } // AccountLiquidity queries struct ResponseAccountLiquidity { IRiskManager.AssetLiquidity[] markets; } function doQueryAccountLiquidity(address eulerContract, address[] memory addrs) external view returns (ResponseAccountLiquidity[] memory r) { Euler eulerProxy = Euler(eulerContract); IExec execProxy = IExec(eulerProxy.moduleIdToProxy(MODULEID__EXEC)); r = new ResponseAccountLiquidity[](addrs.length); for (uint i = 0; i < addrs.length; ++i) { r[i].markets = execProxy.detailedLiquidity(addrs[i]); } } // For tokens like MKR which return bytes32 on name() or symbol() function getStringOrBytes32(address contractAddress, bytes4 selector) private view returns (string memory) { (bool success, bytes memory result) = contractAddress.staticcall(abi.encodeWithSelector(selector)); if (!success) return ""; return result.length == 32 ? string(abi.encodePacked(result)) : abi.decode(result, (string)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Base.sol"; /// @notice Main storage contract for the Euler system contract Euler is Base { constructor(address admin, address installerModule) { emit Genesis(); reentrancyLock = REENTRANCYLOCK__UNLOCKED; upgradeAdmin = admin; governorAdmin = admin; moduleLookup[MODULEID__INSTALLER] = installerModule; address installerProxy = _createProxy(MODULEID__INSTALLER); trustedSenders[installerProxy].moduleImpl = installerModule; } string public constant name = "Euler Protocol"; /// @notice Lookup the current implementation contract for a module /// @param moduleId Fixed constant that refers to a module type (ie MODULEID__ETOKEN) /// @return An internal address specifies the module's implementation code function moduleIdToImplementation(uint moduleId) external view returns (address) { return moduleLookup[moduleId]; } /// @notice Lookup a proxy that can be used to interact with a module (only valid for single-proxy modules) /// @param moduleId Fixed constant that refers to a module type (ie MODULEID__MARKETS) /// @return An address that should be cast to the appropriate module interface, ie IEulerMarkets(moduleIdToProxy(2)) function moduleIdToProxy(uint moduleId) external view returns (address) { return proxyLookup[moduleId]; } function dispatch() external { uint32 moduleId = trustedSenders[msg.sender].moduleId; address moduleImpl = trustedSenders[msg.sender].moduleImpl; require(moduleId != 0, "e/sender-not-trusted"); if (moduleImpl == address(0)) moduleImpl = moduleLookup[moduleId]; uint msgDataLength = msg.data.length; require(msgDataLength >= (4 + 4 + 20), "e/input-too-short"); assembly { let payloadSize := sub(calldatasize(), 4) calldatacopy(0, 4, payloadSize) mstore(payloadSize, shl(96, caller())) let result := delegatecall(gas(), moduleImpl, 0, add(payloadSize, 20), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Constants.sol"; abstract contract Storage is Constants { // Dispatcher and upgrades uint reentrancyLock; address upgradeAdmin; address governorAdmin; mapping(uint => address) moduleLookup; // moduleId => module implementation mapping(uint => address) proxyLookup; // moduleId => proxy address (only for single-proxy modules) struct TrustedSenderInfo { uint32 moduleId; // 0 = un-trusted address moduleImpl; // only non-zero for external single-proxy modules } mapping(address => TrustedSenderInfo) trustedSenders; // sender address => moduleId (0 = un-trusted) // Account-level state // Sub-accounts are considered distinct accounts struct AccountStorage { // Packed slot: 1 + 5 + 4 + 20 = 30 uint8 deferLiquidityStatus; uint40 lastAverageLiquidityUpdate; uint32 numMarketsEntered; address firstMarketEntered; uint averageLiquidity; address averageLiquidityDelegate; } mapping(address => AccountStorage) accountLookup; mapping(address => address[MAX_POSSIBLE_ENTERED_MARKETS]) marketsEntered; // Markets and assets struct AssetConfig { // Packed slot: 20 + 1 + 4 + 4 + 3 = 32 address eTokenAddress; bool borrowIsolated; uint32 collateralFactor; uint32 borrowFactor; uint24 twapWindow; } struct UserAsset { uint112 balance; uint144 owed; uint interestAccumulator; } struct AssetStorage { // Packed slot: 5 + 1 + 4 + 12 + 4 + 2 + 4 = 32 uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; // Not dynamic, but put here to live in same storage slot uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; address underlying; uint96 reserveBalance; address dTokenAddress; uint112 totalBalances; uint144 totalBorrows; uint interestAccumulator; mapping(address => UserAsset) users; mapping(address => mapping(address => uint)) eTokenAllowance; mapping(address => mapping(address => uint)) dTokenAllowance; } mapping(address => AssetConfig) internal underlyingLookup; // underlying => AssetConfig mapping(address => AssetStorage) internal eTokenLookup; // EToken => AssetStorage mapping(address => address) internal dTokenLookup; // DToken => EToken mapping(address => address) internal pTokenLookup; // PToken => underlying mapping(address => address) internal reversePTokenLookup; // underlying => PToken } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "../BaseLogic.sol"; /// @notice Tokenised representation of assets contract EToken is BaseLogic { constructor(bytes32 moduleGitCommit_) BaseLogic(MODULEID__ETOKEN, moduleGitCommit_) {} function CALLER() private view returns (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) { (msgSender, proxyAddr) = unpackTrailingParams(); assetStorage = eTokenLookup[proxyAddr]; underlying = assetStorage.underlying; require(underlying != address(0), "e/unrecognized-etoken-caller"); } // Events event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // External methods /// @notice Pool name, ie "Euler Pool: DAI" function name() external view returns (string memory) { (address underlying,,,) = CALLER(); return string(abi.encodePacked("Euler Pool: ", IERC20(underlying).name())); } /// @notice Pool symbol, ie "eDAI" function symbol() external view returns (string memory) { (address underlying,,,) = CALLER(); return string(abi.encodePacked("e", IERC20(underlying).symbol())); } /// @notice Decimals, always normalised to 18. function decimals() external pure returns (uint8) { return 18; } /// @notice Address of underlying asset function underlyingAsset() external view returns (address) { (address underlying,,,) = CALLER(); return underlying; } /// @notice Sum of all balances, in internal book-keeping units (non-increasing) function totalSupply() external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return assetCache.totalBalances; } /// @notice Sum of all balances, in underlying units (increases as interest is earned) function totalSupplyUnderlying() external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return balanceToUnderlyingAmount(assetCache, assetCache.totalBalances) / assetCache.underlyingDecimalsScaler; } /// @notice Balance of a particular account, in internal book-keeping units (non-increasing) function balanceOf(address account) external view returns (uint) { (, AssetStorage storage assetStorage,,) = CALLER(); return assetStorage.users[account].balance; } /// @notice Balance of a particular account, in underlying units (increases as interest is earned) function balanceOfUnderlying(address account) external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return balanceToUnderlyingAmount(assetCache, assetStorage.users[account].balance) / assetCache.underlyingDecimalsScaler; } /// @notice Balance of the reserves, in internal book-keeping units (non-increasing) function reserveBalance() external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return assetCache.reserveBalance; } /// @notice Balance of the reserves, in underlying units (increases as interest is earned) function reserveBalanceUnderlying() external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return balanceToUnderlyingAmount(assetCache, assetCache.reserveBalance) / assetCache.underlyingDecimalsScaler; } /// @notice Convert an eToken balance to an underlying amount, taking into account current exchange rate /// @param balance eToken balance, in internal book-keeping units (18 decimals) /// @return Amount in underlying units, (same decimals as underlying token) function convertBalanceToUnderlying(uint balance) external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return balanceToUnderlyingAmount(assetCache, balance) / assetCache.underlyingDecimalsScaler; } /// @notice Convert an underlying amount to an eToken balance, taking into account current exchange rate /// @param underlyingAmount Amount in underlying units (same decimals as underlying token) /// @return eToken balance, in internal book-keeping units (18 decimals) function convertUnderlyingToBalance(uint underlyingAmount) external view returns (uint) { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return underlyingAmountToBalance(assetCache, decodeExternalAmount(assetCache, underlyingAmount)); } /// @notice Updates interest accumulator and totalBorrows, credits reserves, re-targets interest rate, and logs asset status function touch() external nonReentrant { (address underlying, AssetStorage storage assetStorage,,) = CALLER(); AssetCache memory assetCache = loadAssetCache(underlying, assetStorage); updateInterestRate(assetStorage, assetCache); logAssetStatus(assetCache); } /// @notice Transfer underlying tokens from sender to the Euler pool, and increase account's eTokens /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param amount In underlying units (use max uint256 for full underlying token balance) function deposit(uint subAccountId, uint amount) external nonReentrant { (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER(); address account = getSubAccount(msgSender, subAccountId); updateAverageLiquidity(account); emit RequestDeposit(account, amount); AssetCache memory assetCache = loadAssetCache(underlying, assetStorage); if (amount == type(uint).max) { amount = callBalanceOf(assetCache, msgSender); } amount = decodeExternalAmount(assetCache, amount); uint amountTransferred = pullTokens(assetCache, msgSender, amount); uint amountInternal; // pullTokens() updates poolSize in the cache, but we need the poolSize before the deposit to determine // the internal amount so temporarily reduce it by the amountTransferred (which is size checked within // pullTokens()). We can't compute this value before the pull because we don't know how much we'll // actually receive (the token might be deflationary). unchecked { assetCache.poolSize -= amountTransferred; amountInternal = underlyingAmountToBalance(assetCache, amountTransferred); assetCache.poolSize += amountTransferred; } increaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal); if (assetStorage.users[account].owed != 0) checkLiquidity(account); logAssetStatus(assetCache); } /// @notice Transfer underlying tokens from Euler pool to sender, and decrease account's eTokens /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param amount In underlying units (use max uint256 for full pool balance) function withdraw(uint subAccountId, uint amount) external nonReentrant { (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER(); address account = getSubAccount(msgSender, subAccountId); updateAverageLiquidity(account); emit RequestWithdraw(account, amount); AssetCache memory assetCache = loadAssetCache(underlying, assetStorage); uint amountInternal; (amount, amountInternal) = withdrawAmounts(assetStorage, assetCache, account, amount); require(assetCache.poolSize >= amount, "e/insufficient-pool-size"); pushTokens(assetCache, msgSender, amount); decreaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal); checkLiquidity(account); logAssetStatus(assetCache); } /// @notice Mint eTokens and a corresponding amount of dTokens ("self-borrow") /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param amount In underlying units function mint(uint subAccountId, uint amount) external nonReentrant { (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER(); address account = getSubAccount(msgSender, subAccountId); updateAverageLiquidity(account); emit RequestMint(account, amount); AssetCache memory assetCache = loadAssetCache(underlying, assetStorage); amount = decodeExternalAmount(assetCache, amount); uint amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount); amount = balanceToUnderlyingAmount(assetCache, amountInternal); // Mint ETokens increaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal); // Mint DTokens increaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, amount); checkLiquidity(account); logAssetStatus(assetCache); } /// @notice Pay off dToken liability with eTokens ("self-repay") /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param amount In underlying units (use max uint256 to repay the debt in full or up to the available underlying balance) function burn(uint subAccountId, uint amount) external nonReentrant { (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER(); address account = getSubAccount(msgSender, subAccountId); updateAverageLiquidity(account); emit RequestBurn(account, amount); AssetCache memory assetCache = loadAssetCache(underlying, assetStorage); uint owed = getCurrentOwed(assetStorage, assetCache, account); if (owed == 0) return; uint amountInternal; (amount, amountInternal) = withdrawAmounts(assetStorage, assetCache, account, amount); if (amount > owed) { amount = owed; amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount); } // Burn ETokens decreaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal); // Burn DTokens decreaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, amount); checkLiquidity(account); logAssetStatus(assetCache); } /// @notice Allow spender to access an amount of your eTokens in sub-account 0 /// @param spender Trusted address /// @param amount Use max uint256 for "infinite" allowance function approve(address spender, uint amount) external reentrantOK returns (bool) { return approveSubAccount(0, spender, amount); } /// @notice Allow spender to access an amount of your eTokens in a particular sub-account /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param spender Trusted address /// @param amount Use max uint256 for "infinite" allowance function approveSubAccount(uint subAccountId, address spender, uint amount) public reentrantOK returns (bool) { (, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER(); address account = getSubAccount(msgSender, subAccountId); require(!isSubAccountOf(spender, account), "e/self-approval"); assetStorage.eTokenAllowance[account][spender] = amount; emitViaProxy_Approval(proxyAddr, account, spender, amount); return true; } /// @notice Retrieve the current allowance /// @param holder Xor with the desired sub-account ID (if applicable) /// @param spender Trusted address function allowance(address holder, address spender) external view returns (uint) { (, AssetStorage storage assetStorage,,) = CALLER(); return assetStorage.eTokenAllowance[holder][spender]; } /// @notice Transfer eTokens to another address (from sub-account 0) /// @param to Xor with the desired sub-account ID (if applicable) /// @param amount In internal book-keeping units (as returned from balanceOf). function transfer(address to, uint amount) external returns (bool) { return transferFrom(address(0), to, amount); } /// @notice Transfer the full eToken balance of an address to another /// @param from This address must've approved the to address, or be a sub-account of msg.sender /// @param to Xor with the desired sub-account ID (if applicable) function transferFromMax(address from, address to) external returns (bool) { (, AssetStorage storage assetStorage,,) = CALLER(); return transferFrom(from, to, assetStorage.users[from].balance); } /// @notice Transfer eTokens from one address to another /// @param from This address must've approved the to address, or be a sub-account of msg.sender /// @param to Xor with the desired sub-account ID (if applicable) /// @param amount In internal book-keeping units (as returned from balanceOf). function transferFrom(address from, address to, uint amount) public nonReentrant returns (bool) { (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER(); AssetCache memory assetCache = loadAssetCache(underlying, assetStorage); if (from == address(0)) from = msgSender; require(from != to, "e/self-transfer"); updateAverageLiquidity(from); updateAverageLiquidity(to); emit RequestTransferEToken(from, to, amount); if (amount == 0) return true; if (!isSubAccountOf(msgSender, from) && assetStorage.eTokenAllowance[from][msgSender] != type(uint).max) { require(assetStorage.eTokenAllowance[from][msgSender] >= amount, "e/insufficient-allowance"); unchecked { assetStorage.eTokenAllowance[from][msgSender] -= amount; } emitViaProxy_Approval(proxyAddr, from, msgSender, assetStorage.eTokenAllowance[from][msgSender]); } transferBalance(assetStorage, assetCache, proxyAddr, from, to, amount); checkLiquidity(from); if (assetStorage.users[to].owed != 0) checkLiquidity(to); logAssetStatus(assetCache); return true; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "../BaseLogic.sol"; import "../IRiskManager.sol"; import "../PToken.sol"; /// @notice Activating and querying markets, and maintaining entered markets lists contract Markets is BaseLogic { constructor(bytes32 moduleGitCommit_) BaseLogic(MODULEID__MARKETS, moduleGitCommit_) {} /// @notice Create an Euler pool and associated EToken and DToken addresses. /// @param underlying The address of an ERC20-compliant token. There must be an initialised uniswap3 pool for the underlying/reference asset pair. /// @return The created EToken, or the existing EToken if already activated. function activateMarket(address underlying) external nonReentrant returns (address) { require(pTokenLookup[underlying] == address(0), "e/markets/invalid-token"); return doActivateMarket(underlying); } function doActivateMarket(address underlying) private returns (address) { // Pre-existing if (underlyingLookup[underlying].eTokenAddress != address(0)) return underlyingLookup[underlying].eTokenAddress; // Validation require(trustedSenders[underlying].moduleId == 0 && underlying != address(this), "e/markets/invalid-token"); uint8 decimals = IERC20(underlying).decimals(); require(decimals <= 18, "e/too-many-decimals"); // Get risk manager parameters IRiskManager.NewMarketParameters memory params; { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getNewMarketParameters.selector, underlying)); (params) = abi.decode(result, (IRiskManager.NewMarketParameters)); } // Create proxies address childEToken = params.config.eTokenAddress = _createProxy(MODULEID__ETOKEN); address childDToken = _createProxy(MODULEID__DTOKEN); // Setup storage underlyingLookup[underlying] = params.config; dTokenLookup[childDToken] = childEToken; AssetStorage storage assetStorage = eTokenLookup[childEToken]; assetStorage.underlying = underlying; assetStorage.pricingType = params.pricingType; assetStorage.pricingParameters = params.pricingParameters; assetStorage.dTokenAddress = childDToken; assetStorage.lastInterestAccumulatorUpdate = uint40(block.timestamp); assetStorage.underlyingDecimals = decimals; assetStorage.interestRateModel = uint32(MODULEID__IRM_DEFAULT); assetStorage.reserveFee = type(uint32).max; // default assetStorage.interestAccumulator = INITIAL_INTEREST_ACCUMULATOR; emit MarketActivated(underlying, childEToken, childDToken); return childEToken; } /// @notice Create a pToken and activate it on Euler. pTokens are protected wrappers around assets that prevent borrowing. /// @param underlying The address of an ERC20-compliant token. There must already be an activated market on Euler for this underlying, and it must have a non-zero collateral factor. /// @return The created pToken, or an existing one if already activated. function activatePToken(address underlying) external nonReentrant returns (address) { require(pTokenLookup[underlying] == address(0), "e/nested-ptoken"); if (reversePTokenLookup[underlying] != address(0)) return reversePTokenLookup[underlying]; { AssetConfig memory config = resolveAssetConfig(underlying); require(config.collateralFactor != 0, "e/ptoken/not-collateral"); } address pTokenAddr = address(new PToken(address(this), underlying)); pTokenLookup[pTokenAddr] = underlying; reversePTokenLookup[underlying] = pTokenAddr; emit PTokenActivated(underlying, pTokenAddr); doActivateMarket(pTokenAddr); return pTokenAddr; } // General market accessors /// @notice Given an underlying, lookup the associated EToken /// @param underlying Token address /// @return EToken address, or address(0) if not activated function underlyingToEToken(address underlying) external view returns (address) { return underlyingLookup[underlying].eTokenAddress; } /// @notice Given an underlying, lookup the associated DToken /// @param underlying Token address /// @return DToken address, or address(0) if not activated function underlyingToDToken(address underlying) external view returns (address) { return eTokenLookup[underlyingLookup[underlying].eTokenAddress].dTokenAddress; } /// @notice Given an underlying, lookup the associated PToken /// @param underlying Token address /// @return PToken address, or address(0) if it doesn't exist function underlyingToPToken(address underlying) external view returns (address) { return reversePTokenLookup[underlying]; } /// @notice Looks up the Euler-related configuration for a token, and resolves all default-value placeholders to their currently configured values. /// @param underlying Token address /// @return Configuration struct function underlyingToAssetConfig(address underlying) external view returns (AssetConfig memory) { return resolveAssetConfig(underlying); } /// @notice Looks up the Euler-related configuration for a token, and returns it unresolved (with default-value placeholders) /// @param underlying Token address /// @return config Configuration struct function underlyingToAssetConfigUnresolved(address underlying) external view returns (AssetConfig memory config) { config = underlyingLookup[underlying]; require(config.eTokenAddress != address(0), "e/market-not-activated"); } /// @notice Given an EToken address, looks up the associated underlying /// @param eToken EToken address /// @return underlying Token address function eTokenToUnderlying(address eToken) external view returns (address underlying) { underlying = eTokenLookup[eToken].underlying; require(underlying != address(0), "e/invalid-etoken"); } /// @notice Given an EToken address, looks up the associated DToken /// @param eToken EToken address /// @return dTokenAddr DToken address function eTokenToDToken(address eToken) external view returns (address dTokenAddr) { dTokenAddr = eTokenLookup[eToken].dTokenAddress; require(dTokenAddr != address(0), "e/invalid-etoken"); } function getAssetStorage(address underlying) private view returns (AssetStorage storage) { address eTokenAddr = underlyingLookup[underlying].eTokenAddress; require(eTokenAddr != address(0), "e/market-not-activated"); return eTokenLookup[eTokenAddr]; } /// @notice Looks up an asset's currently configured interest rate model /// @param underlying Token address /// @return Module ID that represents the interest rate model (IRM) function interestRateModel(address underlying) external view returns (uint) { AssetStorage storage assetStorage = getAssetStorage(underlying); return assetStorage.interestRateModel; } /// @notice Retrieves the current interest rate for an asset /// @param underlying Token address /// @return The interest rate in yield-per-second, scaled by 10**27 function interestRate(address underlying) external view returns (int96) { AssetStorage storage assetStorage = getAssetStorage(underlying); return assetStorage.interestRate; } /// @notice Retrieves the current interest rate accumulator for an asset /// @param underlying Token address /// @return An opaque accumulator that increases as interest is accrued function interestAccumulator(address underlying) external view returns (uint) { AssetStorage storage assetStorage = getAssetStorage(underlying); AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage); return assetCache.interestAccumulator; } /// @notice Retrieves the reserve fee in effect for an asset /// @param underlying Token address /// @return Amount of interest that is redirected to the reserves, as a fraction scaled by RESERVE_FEE_SCALE (4e9) function reserveFee(address underlying) external view returns (uint32) { AssetStorage storage assetStorage = getAssetStorage(underlying); return assetStorage.reserveFee == type(uint32).max ? uint32(DEFAULT_RESERVE_FEE) : assetStorage.reserveFee; } /// @notice Retrieves the pricing config for an asset /// @param underlying Token address /// @return pricingType (1=pegged, 2=uniswap3, 3=forwarded) /// @return pricingParameters If uniswap3 pricingType then this represents the uniswap pool fee used, otherwise unused /// @return pricingForwarded If forwarded pricingType then this is the address prices are forwarded to, otherwise address(0) function getPricingConfig(address underlying) external view returns (uint16 pricingType, uint32 pricingParameters, address pricingForwarded) { AssetStorage storage assetStorage = getAssetStorage(underlying); pricingType = assetStorage.pricingType; pricingParameters = assetStorage.pricingParameters; pricingForwarded = pricingType == PRICINGTYPE__FORWARDED ? pTokenLookup[underlying] : address(0); } // Enter/exit markets /// @notice Retrieves the list of entered markets for an account (assets enabled for collateral or borrowing) /// @param account User account /// @return List of underlying token addresses function getEnteredMarkets(address account) external view returns (address[] memory) { return getEnteredMarketsArray(account); } /// @notice Add an asset to the entered market list, or do nothing if already entered /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param newMarket Underlying token address function enterMarket(uint subAccountId, address newMarket) external nonReentrant { address msgSender = unpackTrailingParamMsgSender(); address account = getSubAccount(msgSender, subAccountId); require(underlyingLookup[newMarket].eTokenAddress != address(0), "e/market-not-activated"); doEnterMarket(account, newMarket); } /// @notice Remove an asset from the entered market list, or do nothing if not already present /// @param subAccountId 0 for primary, 1-255 for a sub-account /// @param oldMarket Underlying token address function exitMarket(uint subAccountId, address oldMarket) external nonReentrant { address msgSender = unpackTrailingParamMsgSender(); address account = getSubAccount(msgSender, subAccountId); AssetConfig memory config = resolveAssetConfig(oldMarket); AssetStorage storage assetStorage = eTokenLookup[config.eTokenAddress]; uint balance = assetStorage.users[account].balance; uint owed = assetStorage.users[account].owed; require(owed == 0, "e/outstanding-borrow"); doExitMarket(account, oldMarket); if (config.collateralFactor != 0 && balance != 0) { checkLiquidity(account); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseIRM.sol"; contract BaseIRMLinearKink is BaseIRM { uint public immutable baseRate; uint public immutable slope1; uint public immutable slope2; uint public immutable kink; constructor(uint moduleId_, bytes32 moduleGitCommit_, uint baseRate_, uint slope1_, uint slope2_, uint kink_) BaseIRM(moduleId_, moduleGitCommit_) { baseRate = baseRate_; slope1 = slope1_; slope2 = slope2_; kink = kink_; } function computeInterestRateImpl(address, uint32 utilisation) internal override view returns (int96) { uint ir = baseRate; if (utilisation <= kink) { ir += utilisation * slope1; } else { ir += kink * slope1; ir += slope2 * (utilisation - kink); } return int96(int(ir)); } } // SPDX-License-Identifier: AGPL-3.0-or-later // From MakerDAO DSS // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; library RPow { function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; //import "hardhat/console.sol"; // DEV_MODE import "./Storage.sol"; import "./Events.sol"; import "./Proxy.sol"; abstract contract Base is Storage, Events { // Modules function _createProxy(uint proxyModuleId) internal returns (address) { require(proxyModuleId != 0, "e/create-proxy/invalid-module"); require(proxyModuleId <= MAX_EXTERNAL_MODULEID, "e/create-proxy/internal-module"); // If we've already created a proxy for a single-proxy module, just return it: if (proxyLookup[proxyModuleId] != address(0)) return proxyLookup[proxyModuleId]; // Otherwise create a proxy: address proxyAddr = address(new Proxy()); if (proxyModuleId <= MAX_EXTERNAL_SINGLE_PROXY_MODULEID) proxyLookup[proxyModuleId] = proxyAddr; trustedSenders[proxyAddr] = TrustedSenderInfo({ moduleId: uint32(proxyModuleId), moduleImpl: address(0) }); emit ProxyCreated(proxyAddr, proxyModuleId); return proxyAddr; } function callInternalModule(uint moduleId, bytes memory input) internal returns (bytes memory) { (bool success, bytes memory result) = moduleLookup[moduleId].delegatecall(input); if (!success) revertBytes(result); return result; } // Modifiers modifier nonReentrant() { require(reentrancyLock == REENTRANCYLOCK__UNLOCKED, "e/reentrancy"); reentrancyLock = REENTRANCYLOCK__LOCKED; _; reentrancyLock = REENTRANCYLOCK__UNLOCKED; } modifier reentrantOK() { // documentation only _; } // Used to flag functions which do not modify storage, but do perform a delegate call // to a view function, which prohibits a standard view modifier. The flag is used to // patch state mutability in compiled ABIs and interfaces. modifier staticDelegate() { _; } // WARNING: Must be very careful with this modifier. It resets the free memory pointer // to the value it was when the function started. This saves gas if more memory will // be allocated in the future. However, if the memory will be later referenced // (for example because the function has returned a pointer to it) then you cannot // use this modifier. modifier FREEMEM() { uint origFreeMemPtr; assembly { origFreeMemPtr := mload(0x40) } _; /* assembly { // DEV_MODE: overwrite the freed memory with garbage to detect bugs let garbage := 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF for { let i := origFreeMemPtr } lt(i, mload(0x40)) { i := add(i, 32) } { mstore(i, garbage) } } */ assembly { mstore(0x40, origFreeMemPtr) } } // Error handling function revertBytes(bytes memory errMsg) internal pure { if (errMsg.length > 0) { assembly { revert(add(32, errMsg), mload(errMsg)) } } revert("e/empty-error"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; abstract contract Events { event Genesis(); event ProxyCreated(address indexed proxy, uint moduleId); event MarketActivated(address indexed underlying, address indexed eToken, address indexed dToken); event PTokenActivated(address indexed underlying, address indexed pToken); event EnterMarket(address indexed underlying, address indexed account); event ExitMarket(address indexed underlying, address indexed account); event Deposit(address indexed underlying, address indexed account, uint amount); event Withdraw(address indexed underlying, address indexed account, uint amount); event Borrow(address indexed underlying, address indexed account, uint amount); event Repay(address indexed underlying, address indexed account, uint amount); event Liquidation(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint yield, uint healthScore, uint baseDiscount, uint discount); event TrackAverageLiquidity(address indexed account); event UnTrackAverageLiquidity(address indexed account); event DelegateAverageLiquidity(address indexed account, address indexed delegate); event PTokenWrap(address indexed underlying, address indexed account, uint amount); event PTokenUnWrap(address indexed underlying, address indexed account, uint amount); event AssetStatus(address indexed underlying, uint totalBalances, uint totalBorrows, uint96 reserveBalance, uint poolSize, uint interestAccumulator, int96 interestRate, uint timestamp); event RequestDeposit(address indexed account, uint amount); event RequestWithdraw(address indexed account, uint amount); event RequestMint(address indexed account, uint amount); event RequestBurn(address indexed account, uint amount); event RequestTransferEToken(address indexed from, address indexed to, uint amount); event RequestBorrow(address indexed account, uint amount); event RequestRepay(address indexed account, uint amount); event RequestTransferDToken(address indexed from, address indexed to, uint amount); event RequestLiquidate(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint minYield); event InstallerSetUpgradeAdmin(address indexed newUpgradeAdmin); event InstallerSetGovernorAdmin(address indexed newGovernorAdmin); event InstallerInstallModule(uint indexed moduleId, address indexed moduleImpl, bytes32 moduleGitCommit); event GovSetAssetConfig(address indexed underlying, Storage.AssetConfig newConfig); event GovSetIRM(address indexed underlying, uint interestRateModel, bytes resetParams); event GovSetPricingConfig(address indexed underlying, uint16 newPricingType, uint32 newPricingParameter); event GovSetReserveFee(address indexed underlying, uint32 newReserveFee); event GovConvertReserves(address indexed underlying, address indexed recipient, uint amount); event RequestSwap(address indexed accountIn, address indexed accountOut, address indexed underlyingIn, address underlyingOut, uint amount, uint swapType); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; contract Proxy { address immutable creator; constructor() { creator = msg.sender; } // External interface fallback() external { address creator_ = creator; if (msg.sender == creator_) { assembly { mstore(0, 0) calldatacopy(31, 0, calldatasize()) switch mload(0) // numTopics case 0 { log0(32, sub(calldatasize(), 1)) } case 1 { log1(64, sub(calldatasize(), 33), mload(32)) } case 2 { log2(96, sub(calldatasize(), 65), mload(32), mload(64)) } case 3 { log3(128, sub(calldatasize(), 97), mload(32), mload(64), mload(96)) } case 4 { log4(160, sub(calldatasize(), 129), mload(32), mload(64), mload(96), mload(128)) } default { revert(0, 0) } return(0, 0) } } else { assembly { mstore(0, 0xe9c4a3ac00000000000000000000000000000000000000000000000000000000) // dispatch() selector calldatacopy(4, 0, calldatasize()) mstore(add(4, calldatasize()), shl(96, caller())) let result := call(gas(), creator_, 0, 0, add(24, calldatasize()), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; abstract contract Constants { // Universal uint internal constant SECONDS_PER_YEAR = 365.2425 * 86400; // Gregorian calendar // Protocol parameters uint internal constant MAX_SANE_AMOUNT = type(uint112).max; uint internal constant MAX_SANE_SMALL_AMOUNT = type(uint96).max; uint internal constant MAX_SANE_DEBT_AMOUNT = type(uint144).max; uint internal constant INTERNAL_DEBT_PRECISION = 1e9; uint internal constant MAX_ENTERED_MARKETS = 10; // per sub-account uint internal constant MAX_POSSIBLE_ENTERED_MARKETS = 2**32; // limited by size of AccountStorage.numMarketsEntered uint internal constant CONFIG_FACTOR_SCALE = 4_000_000_000; // must fit into a uint32 uint internal constant RESERVE_FEE_SCALE = 4_000_000_000; // must fit into a uint32 uint32 internal constant DEFAULT_RESERVE_FEE = uint32(0.23 * 4_000_000_000); uint internal constant INITIAL_INTEREST_ACCUMULATOR = 1e27; uint internal constant AVERAGE_LIQUIDITY_PERIOD = 24 * 60 * 60; uint16 internal constant MIN_UNISWAP3_OBSERVATION_CARDINALITY = 144; uint24 internal constant DEFAULT_TWAP_WINDOW_SECONDS = 30 * 60; uint32 internal constant DEFAULT_BORROW_FACTOR = uint32(0.28 * 4_000_000_000); uint32 internal constant SELF_COLLATERAL_FACTOR = uint32(0.95 * 4_000_000_000); // Implementation internals uint internal constant REENTRANCYLOCK__UNLOCKED = 1; uint internal constant REENTRANCYLOCK__LOCKED = 2; uint8 internal constant DEFERLIQUIDITY__NONE = 0; uint8 internal constant DEFERLIQUIDITY__CLEAN = 1; uint8 internal constant DEFERLIQUIDITY__DIRTY = 2; // Pricing types uint16 internal constant PRICINGTYPE__PEGGED = 1; uint16 internal constant PRICINGTYPE__UNISWAP3_TWAP = 2; uint16 internal constant PRICINGTYPE__FORWARDED = 3; // Modules // Public single-proxy modules uint internal constant MODULEID__INSTALLER = 1; uint internal constant MODULEID__MARKETS = 2; uint internal constant MODULEID__LIQUIDATION = 3; uint internal constant MODULEID__GOVERNANCE = 4; uint internal constant MODULEID__EXEC = 5; uint internal constant MODULEID__SWAP = 6; uint internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999; // Public multi-proxy modules uint internal constant MODULEID__ETOKEN = 500_000; uint internal constant MODULEID__DTOKEN = 500_001; uint internal constant MAX_EXTERNAL_MODULEID = 999_999; // Internal modules uint internal constant MODULEID__RISK_MANAGER = 1_000_000; // Interest rate models // Default for new markets uint internal constant MODULEID__IRM_DEFAULT = 2_000_000; // Testing-only uint internal constant MODULEID__IRM_ZERO = 2_000_001; uint internal constant MODULEID__IRM_FIXED = 2_000_002; uint internal constant MODULEID__IRM_LINEAR = 2_000_100; // Classes uint internal constant MODULEID__IRM_CLASS__STABLE = 2_000_500; uint internal constant MODULEID__IRM_CLASS__MAJOR = 2_000_501; uint internal constant MODULEID__IRM_CLASS__MIDCAP = 2_000_502; uint internal constant MODULEID__IRM_CLASS__MEGA = 2_000_503; // Swap types uint internal constant SWAP_TYPE__UNI_EXACT_INPUT_SINGLE = 1; uint internal constant SWAP_TYPE__UNI_EXACT_INPUT = 2; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE = 3; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT = 4; uint internal constant SWAP_TYPE__1INCH = 5; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY = 6; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY = 7; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; import "./BaseIRM.sol"; import "./Interfaces.sol"; import "./Utils.sol"; import "./vendor/RPow.sol"; import "./IRiskManager.sol"; abstract contract BaseLogic is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} // Account auth function getSubAccount(address primary, uint subAccountId) internal pure returns (address) { require(subAccountId < 256, "e/sub-account-id-too-big"); return address(uint160(primary) ^ uint160(subAccountId)); } function isSubAccountOf(address primary, address subAccount) internal pure returns (bool) { return (uint160(primary) | 0xFF) == (uint160(subAccount) | 0xFF); } // Entered markets array function getEnteredMarketsArray(address account) internal view returns (address[] memory) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; address[] memory output = new address[](numMarketsEntered); if (numMarketsEntered == 0) return output; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; output[0] = firstMarketEntered; for (uint i = 1; i < numMarketsEntered; ++i) { output[i] = markets[i]; } return output; } function isEnteredInMarket(address account, address underlying) internal view returns (bool) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; if (numMarketsEntered == 0) return false; if (firstMarketEntered == underlying) return true; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; for (uint i = 1; i < numMarketsEntered; ++i) { if (markets[i] == underlying) return true; } return false; } function doEnterMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; if (numMarketsEntered != 0) { if (accountStorage.firstMarketEntered == underlying) return; // already entered for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) return; // already entered } } require(numMarketsEntered < MAX_ENTERED_MARKETS, "e/too-many-entered-markets"); if (numMarketsEntered == 0) accountStorage.firstMarketEntered = underlying; else markets[numMarketsEntered] = underlying; accountStorage.numMarketsEntered = numMarketsEntered + 1; emit EnterMarket(underlying, account); } // Liquidity check must be done by caller after calling this function doExitMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; uint searchIndex = type(uint).max; if (numMarketsEntered == 0) return; // already exited if (accountStorage.firstMarketEntered == underlying) { searchIndex = 0; } else { for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) { searchIndex = i; break; } } if (searchIndex == type(uint).max) return; // already exited } uint lastMarketIndex = numMarketsEntered - 1; if (searchIndex != lastMarketIndex) { if (searchIndex == 0) accountStorage.firstMarketEntered = markets[lastMarketIndex]; else markets[searchIndex] = markets[lastMarketIndex]; } accountStorage.numMarketsEntered = uint32(lastMarketIndex); if (lastMarketIndex != 0) markets[lastMarketIndex] = address(0); // zero out for storage refund emit ExitMarket(underlying, account); } // AssetConfig function resolveAssetConfig(address underlying) internal view returns (AssetConfig memory) { AssetConfig memory config = underlyingLookup[underlying]; require(config.eTokenAddress != address(0), "e/market-not-activated"); if (config.borrowFactor == type(uint32).max) config.borrowFactor = DEFAULT_BORROW_FACTOR; if (config.twapWindow == type(uint24).max) config.twapWindow = DEFAULT_TWAP_WINDOW_SECONDS; return config; } // AssetCache struct AssetCache { address underlying; uint112 totalBalances; uint144 totalBorrows; uint96 reserveBalance; uint interestAccumulator; uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; uint poolSize; // result of calling balanceOf on underlying (in external units) uint underlyingDecimalsScaler; uint maxExternalAmount; } function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) { dirty = false; assetCache.underlying = underlying; // Storage loads assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate; uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals; assetCache.interestRateModel = assetStorage.interestRateModel; assetCache.interestRate = assetStorage.interestRate; assetCache.reserveFee = assetStorage.reserveFee; assetCache.pricingType = assetStorage.pricingType; assetCache.pricingParameters = assetStorage.pricingParameters; assetCache.reserveBalance = assetStorage.reserveBalance; assetCache.totalBalances = assetStorage.totalBalances; assetCache.totalBorrows = assetStorage.totalBorrows; assetCache.interestAccumulator = assetStorage.interestAccumulator; // Derived state unchecked { assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals); assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler; } uint poolSize = callBalanceOf(assetCache, address(this)); if (poolSize <= assetCache.maxExternalAmount) { unchecked { assetCache.poolSize = poolSize * assetCache.underlyingDecimalsScaler; } } else { assetCache.poolSize = 0; } // Update interest accumulator and reserves if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) { dirty = true; uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate; // Compute new values uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27; uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator; uint newReserveBalance = assetCache.reserveBalance; uint newTotalBalances = assetCache.totalBalances; uint feeAmount = (newTotalBorrows - assetCache.totalBorrows) * (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee) / (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION); if (feeAmount != 0) { uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION); newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount); newReserveBalance += newTotalBalances - assetCache.totalBalances; } // Store new values in assetCache, only if no overflows will occur if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) { assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows); assetCache.interestAccumulator = newInterestAccumulator; assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp); if (newTotalBalances != assetCache.totalBalances) { assetCache.reserveBalance = encodeSmallAmount(newReserveBalance); assetCache.totalBalances = encodeAmount(newTotalBalances); } } } } function loadAssetCache(address underlying, AssetStorage storage assetStorage) internal returns (AssetCache memory assetCache) { if (initAssetCache(underlying, assetStorage, assetCache)) { assetStorage.lastInterestAccumulatorUpdate = assetCache.lastInterestAccumulatorUpdate; assetStorage.underlying = assetCache.underlying; // avoid an SLOAD of this slot assetStorage.reserveBalance = assetCache.reserveBalance; assetStorage.totalBalances = assetCache.totalBalances; assetStorage.totalBorrows = assetCache.totalBorrows; assetStorage.interestAccumulator = assetCache.interestAccumulator; } } function loadAssetCacheRO(address underlying, AssetStorage storage assetStorage) internal view returns (AssetCache memory assetCache) { initAssetCache(underlying, assetStorage, assetCache); } // Utils function decodeExternalAmount(AssetCache memory assetCache, uint externalAmount) internal pure returns (uint scaledAmount) { require(externalAmount <= assetCache.maxExternalAmount, "e/amount-too-large"); unchecked { scaledAmount = externalAmount * assetCache.underlyingDecimalsScaler; } } function encodeAmount(uint amount) internal pure returns (uint112) { require(amount <= MAX_SANE_AMOUNT, "e/amount-too-large-to-encode"); return uint112(amount); } function encodeSmallAmount(uint amount) internal pure returns (uint96) { require(amount <= MAX_SANE_SMALL_AMOUNT, "e/small-amount-too-large-to-encode"); return uint96(amount); } function encodeDebtAmount(uint amount) internal pure returns (uint144) { require(amount <= MAX_SANE_DEBT_AMOUNT, "e/debt-amount-too-large-to-encode"); return uint144(amount); } function computeExchangeRate(AssetCache memory assetCache) private pure returns (uint) { if (assetCache.totalBalances == 0) return 1e18; return (assetCache.poolSize + (assetCache.totalBorrows / INTERNAL_DEBT_PRECISION)) * 1e18 / assetCache.totalBalances; } function underlyingAmountToBalance(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * 1e18 / exchangeRate; } function underlyingAmountToBalanceRoundUp(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return (amount * 1e18 + (exchangeRate - 1)) / exchangeRate; } function balanceToUnderlyingAmount(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * exchangeRate / 1e18; } function callBalanceOf(AssetCache memory assetCache, address account) internal view FREEMEM returns (uint) { // We set a gas limit so that a malicious token can't eat up all gas and cause a liquidity check to fail. (bool success, bytes memory data) = assetCache.underlying.staticcall{gas: 20000}(abi.encodeWithSelector(IERC20.balanceOf.selector, account)); // If token's balanceOf() call fails for any reason, return 0. This prevents malicious tokens from causing liquidity checks to fail. // If the contract doesn't exist (maybe because selfdestructed), then data.length will be 0 and we will return 0. // Data length > 32 is allowed because some legitimate tokens append extra data that can be safely ignored. if (!success || data.length < 32) return 0; return abi.decode(data, (uint256)); } function updateInterestRate(AssetStorage storage assetStorage, AssetCache memory assetCache) internal { uint32 utilisation; { uint totalBorrows = assetCache.totalBorrows / INTERNAL_DEBT_PRECISION; uint poolAssets = assetCache.poolSize + totalBorrows; if (poolAssets == 0) utilisation = 0; // empty pool arbitrarily given utilisation of 0 else utilisation = uint32(totalBorrows * (uint(type(uint32).max) * 1e18) / poolAssets / 1e18); } bytes memory result = callInternalModule(assetCache.interestRateModel, abi.encodeWithSelector(BaseIRM.computeInterestRate.selector, assetCache.underlying, utilisation)); (int96 newInterestRate) = abi.decode(result, (int96)); assetStorage.interestRate = assetCache.interestRate = newInterestRate; } function logAssetStatus(AssetCache memory a) internal { emit AssetStatus(a.underlying, a.totalBalances, a.totalBorrows / INTERNAL_DEBT_PRECISION, a.reserveBalance, a.poolSize, a.interestAccumulator, a.interestRate, block.timestamp); } // Balances function increaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { assetStorage.users[account].balance = encodeAmount(assetStorage.users[account].balance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(uint(assetCache.totalBalances) + amount); updateInterestRate(assetStorage, assetCache); emit Deposit(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, address(0), account, amount); } function decreaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { uint origBalance = assetStorage.users[account].balance; require(origBalance >= amount, "e/insufficient-balance"); assetStorage.users[account].balance = encodeAmount(origBalance - amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances - amount); updateInterestRate(assetStorage, assetCache); emit Withdraw(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, account, address(0), amount); } function transferBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address from, address to, uint amount) internal { uint origFromBalance = assetStorage.users[from].balance; require(origFromBalance >= amount, "e/insufficient-balance"); uint newFromBalance; unchecked { newFromBalance = origFromBalance - amount; } assetStorage.users[from].balance = encodeAmount(newFromBalance); assetStorage.users[to].balance = encodeAmount(assetStorage.users[to].balance + amount); emit Withdraw(assetCache.underlying, from, amount); emit Deposit(assetCache.underlying, to, amount); emitViaProxy_Transfer(eTokenAddress, from, to, amount); } function withdrawAmounts(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) internal view returns (uint, uint) { uint amountInternal; if (amount == type(uint).max) { amountInternal = assetStorage.users[account].balance; amount = balanceToUnderlyingAmount(assetCache, amountInternal); } else { amount = decodeExternalAmount(assetCache, amount); amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount); } return (amount, amountInternal); } // Borrows // Returns internal precision function getCurrentOwedExact(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint owed) internal view returns (uint) { // Don't bother loading the user's accumulator if (owed == 0) return 0; // Can't divide by 0 here: If owed is non-zero, we must've initialised the user's interestAccumulator return owed * assetCache.interestAccumulator / assetStorage.users[account].interestAccumulator; } // When non-zero, we round *up* to the smallest external unit so that outstanding dust in a loan can be repaid. // unchecked is OK here since owed is always loaded from storage, so we know it fits into a uint144 (pre-interest accural) // Takes and returns 27 decimals precision. function roundUpOwed(AssetCache memory assetCache, uint owed) private pure returns (uint) { if (owed == 0) return 0; unchecked { uint scale = INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler; return (owed + scale - 1) / scale * scale; } } // Returns 18-decimals precision (debt amount is rounded up) function getCurrentOwed(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) internal view returns (uint) { return roundUpOwed(assetCache, getCurrentOwedExact(assetStorage, assetCache, account, assetStorage.users[account].owed)) / INTERNAL_DEBT_PRECISION; } function updateUserBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) private returns (uint newOwedExact, uint prevOwedExact) { prevOwedExact = assetStorage.users[account].owed; newOwedExact = getCurrentOwedExact(assetStorage, assetCache, account, prevOwedExact); assetStorage.users[account].owed = encodeDebtAmount(newOwedExact); assetStorage.users[account].interestAccumulator = assetCache.interestAccumulator; } function logBorrowChange(AssetCache memory assetCache, address dTokenAddress, address account, uint prevOwed, uint owed) private { prevOwed = roundUpOwed(assetCache, prevOwed) / INTERNAL_DEBT_PRECISION; owed = roundUpOwed(assetCache, owed) / INTERNAL_DEBT_PRECISION; if (owed > prevOwed) { uint change = owed - prevOwed; emit Borrow(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, address(0), account, change / assetCache.underlyingDecimalsScaler); } else if (prevOwed > owed) { uint change = prevOwed - owed; emit Repay(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, account, address(0), change / assetCache.underlyingDecimalsScaler); } } function increaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint amount) internal { amount *= INTERNAL_DEBT_PRECISION; require(assetCache.pricingType != PRICINGTYPE__FORWARDED || pTokenLookup[assetCache.underlying] == address(0), "e/borrow-not-supported"); (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); if (owed == 0) doEnterMarket(account, assetCache.underlying); owed += amount; assetStorage.users[account].owed = encodeDebtAmount(owed); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows + amount); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owed); } function decreaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); uint owedRoundedUp = roundUpOwed(assetCache, owed); require(amount <= owedRoundedUp, "e/repay-too-much"); uint owedRemaining; unchecked { owedRemaining = owedRoundedUp - amount; } if (owed > assetCache.totalBorrows) owed = assetCache.totalBorrows; assetStorage.users[account].owed = encodeDebtAmount(owedRemaining); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows - owed + owedRemaining); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owedRemaining); } function transferBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address from, address to, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint fromOwed, uint fromOwedPrev) = updateUserBorrow(assetStorage, assetCache, from); (uint toOwed, uint toOwedPrev) = updateUserBorrow(assetStorage, assetCache, to); if (toOwed == 0) doEnterMarket(to, assetCache.underlying); // If amount was rounded up, transfer exact amount owed if (amount > fromOwed && amount - fromOwed < INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler) amount = fromOwed; require(fromOwed >= amount, "e/insufficient-balance"); unchecked { fromOwed -= amount; } // Transfer any residual dust if (fromOwed < INTERNAL_DEBT_PRECISION) { amount += fromOwed; fromOwed = 0; } toOwed += amount; assetStorage.users[from].owed = encodeDebtAmount(fromOwed); assetStorage.users[to].owed = encodeDebtAmount(toOwed); logBorrowChange(assetCache, dTokenAddress, from, fromOwedPrev, fromOwed); logBorrowChange(assetCache, dTokenAddress, to, toOwedPrev, toOwed); } // Reserves function increaseReserves(AssetStorage storage assetStorage, AssetCache memory assetCache, uint amount) internal { assetStorage.reserveBalance = assetCache.reserveBalance = encodeSmallAmount(assetCache.reserveBalance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances + amount); } // Token asset transfers // amounts are in underlying units function pullTokens(AssetCache memory assetCache, address from, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransferFrom(assetCache.underlying, from, address(this), amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeAfter >= poolSizeBefore, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeAfter - poolSizeBefore; } } function pushTokens(AssetCache memory assetCache, address to, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransfer(assetCache.underlying, to, amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeBefore >= poolSizeAfter, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeBefore - poolSizeAfter; } } // Liquidity function getAssetPrice(address asset) internal returns (uint) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getPrice.selector, asset)); return abi.decode(result, (uint)); } function getAccountLiquidity(address account) internal returns (uint collateralValue, uint liabilityValue) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.computeLiquidity.selector, account)); (IRiskManager.LiquidityStatus memory status) = abi.decode(result, (IRiskManager.LiquidityStatus)); collateralValue = status.collateralValue; liabilityValue = status.liabilityValue; } function checkLiquidity(address account) internal { uint8 status = accountLookup[account].deferLiquidityStatus; if (status == DEFERLIQUIDITY__NONE) { callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.requireLiquidity.selector, account)); } else if (status == DEFERLIQUIDITY__CLEAN) { accountLookup[account].deferLiquidityStatus = DEFERLIQUIDITY__DIRTY; } } // Optional average liquidity tracking function computeNewAverageLiquidity(address account, uint deltaT) private returns (uint) { uint currDuration = deltaT >= AVERAGE_LIQUIDITY_PERIOD ? AVERAGE_LIQUIDITY_PERIOD : deltaT; uint prevDuration = AVERAGE_LIQUIDITY_PERIOD - currDuration; uint currAverageLiquidity; { (uint collateralValue, uint liabilityValue) = getAccountLiquidity(account); currAverageLiquidity = collateralValue > liabilityValue ? collateralValue - liabilityValue : 0; } return (accountLookup[account].averageLiquidity * prevDuration / AVERAGE_LIQUIDITY_PERIOD) + (currAverageLiquidity * currDuration / AVERAGE_LIQUIDITY_PERIOD); } function getUpdatedAverageLiquidity(address account) internal returns (uint) { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return 0; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return accountLookup[account].averageLiquidity; return computeNewAverageLiquidity(account, deltaT); } function getUpdatedAverageLiquidityWithDelegate(address account) internal returns (uint) { address delegate = accountLookup[account].averageLiquidityDelegate; return delegate != address(0) && accountLookup[delegate].averageLiquidityDelegate == account ? getUpdatedAverageLiquidity(delegate) : getUpdatedAverageLiquidity(account); } function updateAverageLiquidity(address account) internal { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return; accountLookup[account].lastAverageLiquidityUpdate = uint40(block.timestamp); accountLookup[account].averageLiquidity = computeNewAverageLiquidity(account, deltaT); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Base.sol"; abstract contract BaseModule is Base { // Construction // public accessors common to all modules uint immutable public moduleId; bytes32 immutable public moduleGitCommit; constructor(uint moduleId_, bytes32 moduleGitCommit_) { moduleId = moduleId_; moduleGitCommit = moduleGitCommit_; } // Accessing parameters function unpackTrailingParamMsgSender() internal pure returns (address msgSender) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) } } function unpackTrailingParams() internal pure returns (address msgSender, address proxyAddr) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) proxyAddr := shr(96, calldataload(sub(calldatasize(), 20))) } } // Emit logs via proxies function emitViaProxy_Transfer(address proxyAddr, address from, address to, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Transfer(address,address,uint256)')), bytes32(uint(uint160(from))), bytes32(uint(uint160(to))), value )); require(success, "e/log-proxy-fail"); } function emitViaProxy_Approval(address proxyAddr, address owner, address spender, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Approval(address,address,uint256)')), bytes32(uint(uint160(owner))), bytes32(uint(uint160(spender))), value )); require(success, "e/log-proxy-fail"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; abstract contract BaseIRM is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} int96 internal constant MAX_ALLOWED_INTEREST_RATE = int96(int(uint(5 * 1e27) / SECONDS_PER_YEAR)); // 500% APR int96 internal constant MIN_ALLOWED_INTEREST_RATE = 0; function computeInterestRateImpl(address, uint32) internal virtual returns (int96); function computeInterestRate(address underlying, uint32 utilisation) external returns (int96) { int96 rate = computeInterestRateImpl(underlying, utilisation); if (rate > MAX_ALLOWED_INTEREST_RATE) rate = MAX_ALLOWED_INTEREST_RATE; else if (rate < MIN_ALLOWED_INTEREST_RATE) rate = MIN_ALLOWED_INTEREST_RATE; return rate; } function reset(address underlying, bytes calldata resetParams) external virtual {} } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function 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); } interface IERC20Permit { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external; } interface IERC3156FlashBorrower { function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32); } interface IERC3156FlashLender { function maxFlashLoan(address token) external view returns (uint256); function flashFee(address token, uint256 amount) external view returns (uint256); function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Interfaces.sol"; library Utils { function safeTransferFrom(address token, address from, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; // This interface is used to avoid a circular dependency between BaseLogic and RiskManager interface IRiskManager { struct NewMarketParameters { uint16 pricingType; uint32 pricingParameters; Storage.AssetConfig config; } struct LiquidityStatus { uint collateralValue; uint liabilityValue; uint numBorrows; bool borrowIsolated; } struct AssetLiquidity { address underlying; LiquidityStatus status; } function getNewMarketParameters(address underlying) external returns (NewMarketParameters memory); function requireLiquidity(address account) external view; function computeLiquidity(address account) external view returns (LiquidityStatus memory status); function computeAssetLiquidities(address account) external view returns (AssetLiquidity[] memory assets); function getPrice(address underlying) external view returns (uint twap, uint twapPeriod); function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Interfaces.sol"; import "./Utils.sol"; /// @notice Protected Tokens are simple wrappers for tokens, allowing you to use tokens as collateral without permitting borrowing contract PToken { address immutable euler; address immutable underlyingToken; constructor(address euler_, address underlying_) { euler = euler_; underlyingToken = underlying_; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowances; uint totalBalances; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); /// @notice PToken name, ie "Euler Protected DAI" function name() external view returns (string memory) { return string(abi.encodePacked("Euler Protected ", IERC20(underlyingToken).name())); } /// @notice PToken symbol, ie "pDAI" function symbol() external view returns (string memory) { return string(abi.encodePacked("p", IERC20(underlyingToken).symbol())); } /// @notice Number of decimals, which is same as the underlying's function decimals() external view returns (uint8) { return IERC20(underlyingToken).decimals(); } /// @notice Address of the underlying asset function underlying() external view returns (address) { return underlyingToken; } /// @notice Balance of an account's wrapped tokens function balanceOf(address who) external view returns (uint) { return balances[who]; } /// @notice Sum of all wrapped token balances function totalSupply() external view returns (uint) { return totalBalances; } /// @notice Retrieve the current allowance /// @param holder Address giving permission to access tokens /// @param spender Trusted address function allowance(address holder, address spender) external view returns (uint) { return allowances[holder][spender]; } /// @notice Transfer your own pTokens to another address /// @param recipient Recipient address /// @param amount Amount of wrapped token to transfer function transfer(address recipient, uint amount) external returns (bool) { return transferFrom(msg.sender, recipient, amount); } /// @notice Transfer pTokens from one address to another. The euler address is automatically granted approval. /// @param from This address must've approved the to address /// @param recipient Recipient address /// @param amount Amount to transfer function transferFrom(address from, address recipient, uint amount) public returns (bool) { require(balances[from] >= amount, "insufficient balance"); if (from != msg.sender && msg.sender != euler && allowances[from][msg.sender] != type(uint).max) { require(allowances[from][msg.sender] >= amount, "insufficient allowance"); allowances[from][msg.sender] -= amount; emit Approval(from, msg.sender, allowances[from][msg.sender]); } balances[from] -= amount; balances[recipient] += amount; emit Transfer(from, recipient, amount); return true; } /// @notice Allow spender to access an amount of your pTokens. It is not necessary to approve the euler address. /// @param spender Trusted address /// @param amount Use max uint256 for "infinite" allowance function approve(address spender, uint amount) external returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @notice Convert underlying tokens to pTokens /// @param amount In underlying units (which are equivalent to pToken units) function wrap(uint amount) external { Utils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount); claimSurplus(msg.sender); } /// @notice Convert pTokens to underlying tokens /// @param amount In pToken units (which are equivalent to underlying units) function unwrap(uint amount) external { doUnwrap(msg.sender, amount); } // Only callable by the euler contract: function forceUnwrap(address who, uint amount) external { require(msg.sender == euler, "permission denied"); doUnwrap(who, amount); } /// @notice Claim any surplus tokens held by the PToken contract. This should only be used by contracts. /// @param who Beneficiary to be credited for the surplus token amount function claimSurplus(address who) public { uint currBalance = IERC20(underlyingToken).balanceOf(address(this)); require(currBalance > totalBalances, "no surplus balance to claim"); uint amount = currBalance - totalBalances; totalBalances += amount; balances[who] += amount; emit Transfer(address(0), who, amount); } // Internal shared: function doUnwrap(address who, uint amount) private { require(balances[who] >= amount, "insufficient balance"); totalBalances -= amount; balances[who] -= amount; Utils.safeTransfer(underlyingToken, who, amount); emit Transfer(who, address(0), amount); } }
Given an EToken address, looks up the associated DToken eToken EToken address return dTokenAddr DToken address
function eTokenToDToken(address eToken) external view returns (address dTokenAddr) { dTokenAddr = eTokenLookup[eToken].dTokenAddress; require(dTokenAddr != address(0), "e/invalid-etoken"); }
144,908
./full_match/137/0xdc6ac48890586A83c17E4c95CaE1C867E56b8260/sources/project_/contracts/libraries/LiquidityPools.sol
Debit wallet Pair token balance and credit fee wallet reserve asset balances
function executeAddLiquidity( Storage storage self, LiquidityAddition memory addition, LiquidityChangeExecution memory execution, address feeWallet, address custodianAddress, BalanceTracking.Storage storage balanceTracking ) external { ILiquidityProviderToken liquidityProviderToken = validateAndUpdateForLiquidityAddition(self, addition, execution); balanceTracking.updateForAddLiquidity( addition, execution, feeWallet, custodianAddress, liquidityProviderToken ); }
4,691,631
./full_match/1/0x13Bdb00E3Ad547aD392E9B4f1f91EDE8ACDb77CF/sources/contracts/CIV-Vault.sol
Fetches the user information for a given strategy _id. _id The _id of the strategy to fetch the information for. _epoch The starting index to fetch the information for. return users An array of addresses of unique depositors./ Initialize the return array with the size equal to the range between the start and end indices Loop through the mapping to populate the return array
function getDepositors( uint _id, uint _epoch ) external view checkStrategyExistence(_id) returns (address[] memory users) { users = new address[](_epochInfo[_id][_epoch].totDepositors); for (uint i = 0; i < _epochInfo[_id][_epoch].totDepositors; i++) { users[i] = _depositors[_id][_epoch][i]; } }
9,693,330
pragma solidity ^0.6.0; import "./PublicMultiSig.sol"; /** * @title SecretMultiSig * @dev SecretMultiSig contract * Use the KECCAK256 to hide the transaction details * The details only need to be revealed at the execution time * * @author Cyril Lapinte - <[email protected]> * SPDX-License-Identifier: MIT * * Error messages * SMS01: Only revealed transaction can be executed * SMS02: Hash must not be empty * SMS03: TransactionId must reference an existing transaction * SMS04: Transaction has already been revealed * SMS05: Revealed transaction hash does not matched */ contract SecretMultiSig is PublicMultiSig { struct SecretTransaction { bytes32 hash; bool revealed; } mapping(uint256 => SecretTransaction) internal privateTransactions; /** * @dev contructor **/ constructor( uint256 _threshold, uint256 _duration, address[] memory _participants, uint256[] memory _weights ) public PublicMultiSig(_threshold, _duration, _participants, _weights) {} // solhint-disable-line no-empty-blocks /** * @dev is the transaction revealed */ function isRevealed(uint256 _transactionId) public view returns (bool) { return privateTransactions[_transactionId].revealed; } /** * @dev is the transaction executable */ function isExecutable(uint256 _transactionId) public override view returns (bool) { return isRevealed(_transactionId) && super.isExecutable(_transactionId); } /** * @dev execute the transaction if it has been revealed */ function execute(uint256 _transactionId) public override returns (bool) { require(isRevealed(_transactionId), "SMS01"); return super.execute(_transactionId); } /** * @dev prepare a transaction hash */ function buildHash( uint256 _transactionId, uint256 _salt, address _destination, uint256 _value, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _transactionId, _salt, _destination, _value, _data ) ); } /** * @dev execute the transaction hash without revealing it first */ function executeHash( uint256 _transactionId, uint256 _salt, address payable _destination, uint256 _value, bytes memory _data ) public returns (bool) { revealHash( _transactionId, _salt, _destination, _value, _data ); execute(_transactionId); return true; } /** * @dev suggest a new transaction */ function suggest(address payable _destination, uint256 _value, bytes memory _data) public override returns (bool) { privateTransactions[transactionCount_] = SecretTransaction("", true); return super.suggest(_destination, _value, _data); } /** * @dev suggest a new transaction in providing the hash */ function suggestHash(bytes32 _hash) public returns (bool) { require(_hash != "", "SMS02"); privateTransactions[transactionCount_] = SecretTransaction(_hash, false); transactions[transactionCount_] = Transaction( address(0), 0, "", 0, false, false, msg.sender, // solhint-disable-next-line not-rely-on-time now, false ); emit TransactionAdded(transactionCount_); transactionCount_++; return true; } /** * @dev reveal a transaction hash */ function revealHash( uint256 _transactionId, uint256 _salt, address payable _destination, uint256 _value, bytes memory _data) public returns (bool) { require(_transactionId < transactionCount_, "SMS03"); SecretTransaction storage privateTransaction = privateTransactions[_transactionId]; require(!privateTransaction.revealed, "SMS04"); require( privateTransaction.hash == buildHash( _transactionId, _salt, _destination, _value, _data ), "SMS05" ); privateTransaction.revealed = true; Transaction storage transaction = transactions[_transactionId]; transaction.destination = _destination; transaction.value = _value; transaction.data = _data; emit TransactionRevealed(_transactionId); return true; } event TransactionRevealed(uint256 transactionId); }
execute the transaction hash without revealing it first/
function executeHash( uint256 _transactionId, uint256 _salt, address payable _destination, uint256 _value, bytes memory _data ) public returns (bool) { revealHash( _transactionId, _salt, _destination, _value, _data ); execute(_transactionId); return true; }
12,864,659
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; ///@author @developerasun /* 1. You should be running a blockchain to check balance transfer. Try hardhat or ganache. 2. The amount of Ether will be moved from msg.sender to receiver. Check blockchain logs in above network. 3. Among send, transfer, call methods, call with reentrancy guard is recommended for Ether transfer because of gas cost and security. */ contract MyPayable { function getBalance(address _user) public view returns(uint256) { uint256 amount = address(_user).balance ; return amount; } // method to send Ether 1: address.transfer, 2300 gas, throws error function transferEth(address payable receiver) public payable { receiver.transfer(msg.value); // msg.value : number of wei sent with the message } // method to send Ether 2: address.send => 2300 gas, returns bool function sendEthe(address payable receiver) public payable { bool isSent = receiver.send(msg.value); require(isSent, "Sending Ether failed"); } // method to send Ether 3: address.call => forward all gas, returns bool // Which method should you use? // call in combination with re-entrancy guard is the recommended method to use after December 2019. // Guard against re-entrancy by making all state changes // before calling other contracts using re-entrancy guard modifier function callEth(address payable receiver) public payable { // call method returns bool and bytes memory // The empty argument triggers the fallback function of the receiving address. (bool isSent, ) = receiver.call{gas: 10000, value : msg.value}(""); require(isSent); } // Function to receive Ether. msg.data must be empty receive() external payable {} // receive takes no argument, cannot have returns, should be external // Fallback function is called when msg.data is not empty // using fallback is not recommended because of the interface confusion failure fallback() external payable {} }
method to send Ether 3: address.call => forward all gas, returns bool Which method should you use? call in combination with re-entrancy guard is the recommended method to use after December 2019. Guard against re-entrancy by making all state changes before calling other contracts using re-entrancy guard modifier call method returns bool and bytes memory The empty argument triggers the fallback function of the receiving address.
function callEth(address payable receiver) public payable { require(isSent); }
1,006,375
./partial_match/1/0x000000F20032b9e171844B00EA507E11960BD94a/sources/src/clones/ERC1155SeaDropContractOffererCloneable.sol
Internal function to mint tokens during a generateOrder call from Seaport. data The original transaction calldata, without the selector./ Decode fulfiller, minimumReceived, and context from calldata. Assign the minter from context[22:42]. We validate context has the correct minimum length in the implementation's `_decodeOrder`. If the minter is the zero address, set it to the fulfiller.
function _mintOrder(bytes calldata data) internal { ( address fulfiller, SpentItem[] memory minimumReceived, , bytes memory context ) = abi.decode(data, (address, SpentItem[], SpentItem[], bytes)); address minter; assembly { minter := shr(96, mload(add(add(context, 0x20), 22))) } if (minter == address(0)) { minter = fulfiller; } uint256[] memory tokenIds = new uint256[](minimumReceivedLength); uint256[] memory quantities = new uint256[](minimumReceivedLength); for (uint256 i = 0; i < minimumReceivedLength; ) { tokenIds[i] = minimumReceived[i].identifier; quantities[i] = minimumReceived[i].amount; unchecked { ++i; } } }
2,652,421
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IERC20Ubiquity.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "./interfaces/IExcessDollarsDistributor.sol"; import "./interfaces/IMetaPool.sol"; import "./UbiquityAlgorithmicDollarManager.sol"; import "./SushiSwapPool.sol"; import "./libs/ABDKMathQuad.sol"; /// @title An excess dollar distributor which sends dollars to treasury, /// lp rewards and inflation rewards contract ExcessDollarsDistributor is IExcessDollarsDistributor { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private immutable _minAmountToDistribute = 100 ether; IUniswapV2Router02 private immutable _router = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiV2Router02 /// @param _manager the address of the manager contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function distributeDollars() external override { //the excess dollars which were sent to this contract by the coupon manager uint256 excessDollars = IERC20Ubiquity(manager.dollarTokenAddress()).balanceOf( address(this) ); if (excessDollars > _minAmountToDistribute) { address treasuryAddress = manager.treasuryAddress(); // curve uAD-3CRV liquidity pool uint256 tenPercent = excessDollars.fromUInt().div(uint256(10).fromUInt()).toUInt(); uint256 fiftyPercent = excessDollars.fromUInt().div(uint256(2).fromUInt()).toUInt(); IERC20Ubiquity(manager.dollarTokenAddress()).safeTransfer( treasuryAddress, fiftyPercent ); // convert uAD to uGOV-UAD LP on sushi and burn them _governanceBuyBackLPAndBurn(tenPercent); // convert remaining uAD to curve LP tokens // and transfer the curve LP tokens to the bonding contract _convertToCurveLPAndTransfer( excessDollars - fiftyPercent - tenPercent ); } } // swap half amount to uGOV function _swapDollarsForGovernance(bytes16 amountIn) internal returns (uint256) { address[] memory path = new address[](2); path[0] = manager.dollarTokenAddress(); path[1] = manager.governanceTokenAddress(); uint256[] memory amounts = _router.swapExactTokensForTokens( amountIn.toUInt(), 0, path, address(this), block.timestamp + 100 ); return amounts[1]; } // buy-back and burn uGOV function _governanceBuyBackLPAndBurn(uint256 amount) internal { bytes16 amountUAD = (amount.fromUInt()).div(uint256(2).fromUInt()); // we need to approve sushi router IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), amount ); uint256 amountUGOV = _swapDollarsForGovernance(amountUAD); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), amountUGOV ); // deposit liquidity and transfer to zero address (burn) _router.addLiquidity( manager.dollarTokenAddress(), manager.governanceTokenAddress(), amountUAD.toUInt(), amountUGOV, 0, 0, address(0), block.timestamp + 100 ); } // @dev convert to curve LP // @param amount to convert to curve LP by swapping to 3CRV // and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens // the LP token are sent to the bonding contract function _convertToCurveLPAndTransfer(uint256 amount) internal returns (uint256) { // we need to approve metaPool IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount ); // swap amount of uAD => 3CRV uint256 amount3CRVReceived = IMetaPool(manager.stableSwapMetaPoolAddress()).exchange( 0, 1, amount, 0 ); // approve metapool to transfer our 3CRV IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount3CRVReceived ); // deposit liquidity uint256 res = IMetaPool(manager.stableSwapMetaPoolAddress()).add_liquidity( [0, amount3CRVReceived], 0, manager.bondingContractAddress() ); // update TWAP price return res; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ERC20 Ubiquiti preset interface /// @author Ubiquity Algorithmic Dollar interface IERC20Ubiquity is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning(address indexed _burned, uint256 _amount); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.6.2; 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.8.3; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; /// @title A mechanism for distributing excess dollars to relevant places interface IExcessDollarsDistributor { function distributeDollars() external; } // SPDX-License-Identifier: UNLICENSED // !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !! pragma solidity ^0.8.3; interface IMetaPool { event Transfer( address indexed sender, address indexed receiver, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); event TokenExchange( address indexed buyer, int128 sold_id, uint256 tokens_sold, int128 bought_id, uint256 tokens_bought ); event TokenExchangeUnderlying( address indexed buyer, int128 sold_id, uint256 tokens_sold, int128 bought_id, uint256 tokens_bought ); event AddLiquidity( address indexed provider, uint256[2] token_amounts, uint256[2] fees, uint256 invariant, uint256 token_supply ); event RemoveLiquidity( address indexed provider, uint256[2] token_amounts, uint256[2] fees, uint256 token_supply ); event RemoveLiquidityOne( address indexed provider, uint256 token_amount, uint256 coin_amount, uint256 token_supply ); event RemoveLiquidityImbalance( address indexed provider, uint256[2] token_amounts, uint256[2] fees, uint256 invariant, uint256 token_supply ); event CommitNewAdmin(uint256 indexed deadline, address indexed admin); event NewAdmin(address indexed admin); event CommitNewFee( uint256 indexed deadline, uint256 fee, uint256 admin_fee ); event NewFee(uint256 fee, uint256 admin_fee); event RampA( uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time ); event StopRampA(uint256 A, uint256 t); function initialize( string memory _name, string memory _symbol, address _coin, uint256 _decimals, uint256 _A, uint256 _fee, address _admin ) external; function decimals() external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function get_previous_balances() external view returns (uint256[2] memory); function get_balances() external view returns (uint256[2] memory); function get_twap_balances( uint256[2] memory _first_balances, uint256[2] memory _last_balances, uint256 _time_elapsed ) external view returns (uint256[2] memory); function get_price_cumulative_last() external view returns (uint256[2] memory); function admin_fee() external view returns (uint256); function A() external view returns (uint256); function A_precise() external view returns (uint256); function get_virtual_price() external view returns (uint256); function calc_token_amount(uint256[2] memory _amounts, bool _is_deposit) external view returns (uint256); function calc_token_amount( uint256[2] memory _amounts, bool _is_deposit, bool _previous ) external view returns (uint256); function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external returns (uint256); function add_liquidity( uint256[2] memory _amounts, uint256 _min_mint_amount, address _receiver ) external returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy( int128 i, int128 j, uint256 dx, uint256[2] memory _balances ) external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx, uint256[2] memory _balances ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver ) external returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, address _receiver ) external returns (uint256); function remove_liquidity( uint256 _burn_amount, uint256[2] memory _min_amounts ) external returns (uint256[2] memory); function remove_liquidity( uint256 _burn_amount, uint256[2] memory _min_amounts, address _receiver ) external returns (uint256[2] memory); function remove_liquidity_imbalance( uint256[2] memory _amounts, uint256 _max_burn_amount ) external returns (uint256); function remove_liquidity_imbalance( uint256[2] memory _amounts, uint256 _max_burn_amount, address _receiver ) external returns (uint256); function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256); function calc_withdraw_one_coin( uint256 _burn_amount, int128 i, bool _previous ) external view returns (uint256); function remove_liquidity_one_coin( uint256 _burn_amount, int128 i, uint256 _min_received ) external returns (uint256); function remove_liquidity_one_coin( uint256 _burn_amount, int128 i, uint256 _min_received, address _receiver ) external returns (uint256); function ramp_A(uint256 _future_A, uint256 _future_time) external; function stop_ramp_A() external; function admin_balances(uint256 i) external view returns (uint256); function withdraw_admin_fees() external; function admin() external view returns (address); function coins(uint256 arg0) external view returns (address); function balances(uint256 arg0) external view returns (uint256); function fee() external view returns (uint256); function block_timestamp_last() external view returns (uint256); function initial_A() external view returns (uint256); function future_A() external view returns (uint256); function initial_A_time() external view returns (uint256); function future_A_time() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function balanceOf(address arg0) external view returns (uint256); function allowance(address arg0, address arg1) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IUbiquityAlgorithmicDollar.sol"; import "./interfaces/ICurveFactory.sol"; import "./interfaces/IMetaPool.sol"; import "./TWAPOracle.sol"; /// @title A central config for the uAD system. Also acts as a central /// access control manager. /// @notice For storing constants. For storing variables and allowing them to /// be changed by the admin (governance) /// @dev This should be used as a central access control manager which other /// contracts use to check permissions contract UbiquityAlgorithmicDollarManager is AccessControl { using SafeERC20 for IERC20; bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE"); bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER"); bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER"); bytes32 public constant INCENTIVE_MANAGER_ROLE = keccak256("INCENTIVE_MANAGER"); bytes32 public constant UBQ_TOKEN_MANAGER_ROLE = keccak256("UBQ_TOKEN_MANAGER_ROLE"); address public twapOracleAddress; address public debtCouponAddress; address public dollarTokenAddress; // uAD address public couponCalculatorAddress; address public dollarMintingCalculatorAddress; address public bondingShareAddress; address public bondingContractAddress; address public stableSwapMetaPoolAddress; address public curve3PoolTokenAddress; // 3CRV address public treasuryAddress; address public governanceTokenAddress; // uGOV address public sushiSwapPoolAddress; // sushi pool uAD-uGOV address public masterChefAddress; address public formulasAddress; address public autoRedeemTokenAddress; // uAR address public uarCalculatorAddress; // uAR calculator //key = address of couponmanager, value = excessdollardistributor mapping(address => address) private _excessDollarDistributors; modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "uADMGR: Caller is not admin" ); _; } constructor(address _admin) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(UBQ_MINTER_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupRole(COUPON_MANAGER_ROLE, _admin); _setupRole(BONDING_MANAGER_ROLE, _admin); _setupRole(INCENTIVE_MANAGER_ROLE, _admin); _setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this)); } // TODO Add a generic setter for extra addresses that needs to be linked function setTwapOracleAddress(address _twapOracleAddress) external onlyAdmin { twapOracleAddress = _twapOracleAddress; // to be removed TWAPOracle oracle = TWAPOracle(twapOracleAddress); oracle.update(); } function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin { autoRedeemTokenAddress = _uarTokenAddress; } function setDebtCouponAddress(address _debtCouponAddress) external onlyAdmin { debtCouponAddress = _debtCouponAddress; } function setIncentiveToUAD(address _account, address _incentiveAddress) external onlyAdmin { IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract( _account, _incentiveAddress ); } function setDollarTokenAddress(address _dollarTokenAddress) external onlyAdmin { dollarTokenAddress = _dollarTokenAddress; } function setGovernanceTokenAddress(address _governanceTokenAddress) external onlyAdmin { governanceTokenAddress = _governanceTokenAddress; } function setSushiSwapPoolAddress(address _sushiSwapPoolAddress) external onlyAdmin { sushiSwapPoolAddress = _sushiSwapPoolAddress; } function setUARCalculatorAddress(address _uarCalculatorAddress) external onlyAdmin { uarCalculatorAddress = _uarCalculatorAddress; } function setCouponCalculatorAddress(address _couponCalculatorAddress) external onlyAdmin { couponCalculatorAddress = _couponCalculatorAddress; } function setDollarMintingCalculatorAddress( address _dollarMintingCalculatorAddress ) external onlyAdmin { dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress; } function setExcessDollarsDistributor( address debtCouponManagerAddress, address excessCouponDistributor ) external onlyAdmin { _excessDollarDistributors[ debtCouponManagerAddress ] = excessCouponDistributor; } function setMasterChefAddress(address _masterChefAddress) external onlyAdmin { masterChefAddress = _masterChefAddress; } function setFormulasAddress(address _formulasAddress) external onlyAdmin { formulasAddress = _formulasAddress; } function setBondingShareAddress(address _bondingShareAddress) external onlyAdmin { bondingShareAddress = _bondingShareAddress; } function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress) external onlyAdmin { stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress; } /** @notice set the bonding bontract smart contract address @dev bonding contract participants deposit curve LP token for a certain duration to earn uGOV and more curve LP token @param _bondingContractAddress bonding contract address */ function setBondingContractAddress(address _bondingContractAddress) external onlyAdmin { bondingContractAddress = _bondingContractAddress; } /** @notice set the treasury address @dev the treasury fund is used to maintain the protocol @param _treasuryAddress treasury fund address */ function setTreasuryAddress(address _treasuryAddress) external onlyAdmin { treasuryAddress = _treasuryAddress; } /** @notice deploy a new Curve metapools for uAD Token uAD/3Pool @dev From the curve documentation for uncollateralized algorithmic stablecoins amplification should be 5-10 @param _curveFactory MetaPool factory address @param _crvBasePool Address of the base pool to use within the new metapool. @param _crv3PoolTokenAddress curve 3Pool token Address @param _amplificationCoefficient amplification coefficient. The smaller it is the closer to a constant product we are. @param _fee Trade fee, given as an integer with 1e10 precision. */ function deployStableSwapPool( address _curveFactory, address _crvBasePool, address _crv3PoolTokenAddress, uint256 _amplificationCoefficient, uint256 _fee ) external onlyAdmin { // Create new StableSwap meta pool (uAD <-> 3Crv) address metaPool = ICurveFactory(_curveFactory).deploy_metapool( _crvBasePool, ERC20(dollarTokenAddress).name(), ERC20(dollarTokenAddress).symbol(), dollarTokenAddress, _amplificationCoefficient, _fee ); stableSwapMetaPoolAddress = metaPool; // Approve the newly-deployed meta pool to transfer this contract's funds uint256 crv3PoolTokenAmount = IERC20(_crv3PoolTokenAddress).balanceOf(address(this)); uint256 uADTokenAmount = IERC20(dollarTokenAddress).balanceOf(address(this)); // safe approve revert if approve from non-zero to non-zero allowance IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0); IERC20(_crv3PoolTokenAddress).safeApprove( metaPool, crv3PoolTokenAmount ); IERC20(dollarTokenAddress).safeApprove(metaPool, 0); IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount); // coin at index 0 is uAD and index 1 is 3CRV require( IMetaPool(metaPool).coins(0) == dollarTokenAddress && IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress, "uADMGR: COIN_ORDER_MISMATCH" ); // Add the initial liquidity to the StableSwap meta pool uint256[2] memory amounts = [ IERC20(dollarTokenAddress).balanceOf(address(this)), IERC20(_crv3PoolTokenAddress).balanceOf(address(this)) ]; // set curve 3Pool address curve3PoolTokenAddress = _crv3PoolTokenAddress; IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender); } function getExcessDollarsDistributor(address _debtCouponManagerAddress) external view returns (address) { return _excessDollarDistributors[_debtCouponManagerAddress]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "./UbiquityAlgorithmicDollarManager.sol"; contract SushiSwapPool { IUniswapV2Factory public factory = IUniswapV2Factory(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac); UbiquityAlgorithmicDollarManager public manager; IUniswapV2Pair public pair; constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); require( manager.dollarTokenAddress() != address(0), "Dollar address not set" ); require( manager.governanceTokenAddress() != address(0), "uGOV Address not set" ); // check if pair already exist address pool = factory.getPair( manager.dollarTokenAddress(), manager.governanceTokenAddress() ); if (pool == address(0)) { pool = factory.createPair( manager.dollarTokenAddress(), manager.governanceTokenAddress() ); } pair = IUniswapV2Pair(pool); } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with 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) { unchecked { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint256(x > 0 ? x : -x); uint256 msb = mostSignificantBit(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) { unchecked { 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) { unchecked { if (x == 0) return bytes16(0); else { uint256 result = x; uint256 msb = mostSignificantBit(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) { unchecked { 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) { unchecked { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint256(x > 0 ? x : -x); uint256 msb = mostSignificantBit(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) { unchecked { 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) { unchecked { if (x == 0) return bytes16(0); else { // We rely on overflow behavior here uint256 result = uint128(x > 0 ? x : -x); uint256 msb = mostSignificantBit(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) { unchecked { 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(int256(result)); // We rely on overflow behavior here } else { require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(int256(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) { unchecked { 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) { unchecked { 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 = mostSignificantBit(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) { unchecked { 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 = mostSignificantBit(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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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) { unchecked { 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 = mostSignificantBit(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) { unchecked {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) { unchecked { 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 : mostSignificantBit(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) { unchecked { 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 - mostSignificantBit(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 ? mostSignificantBit(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) { unchecked {return x ^ 0x80000000000000000000000000000000;} } /** * Calculate |x|. * * @param x quadruple precision number * @return quadruple precision number */ function abs(bytes16 x) internal pure returns (bytes16) { unchecked {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) { unchecked { 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 = mostSignificantBit(xSignifier); uint256 shift = (226 - msb) & 0xFE; xSignifier <<= shift; xExponent -= (shift - 112) >> 1; } } else { if (xSignifier >= 0x10000000000000000000000000000) xSignifier <<= 112; else { uint256 msb = mostSignificantBit(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) { unchecked { 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 = mostSignificantBit(xSignifier); resultSignifier = 16493 - msb; xSignifier <<= 127 - msb; } } if (xSignifier == 0x80000000000000000000000000000000) { if (resultNegative) resultSignifier += 1; uint256 shift = 112 - mostSignificantBit(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) { unchecked {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) { unchecked { 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) { unchecked {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 mostSignificantBit(uint256 x) private pure returns (uint256) { unchecked { 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.6.2; 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _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.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "./IERC20Ubiquity.sol"; /// @title UAD stablecoin interface /// @author Ubiquity Algorithmic Dollar interface IUbiquityAlgorithmicDollar is IERC20Ubiquity { event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); function setIncentiveContract(address account, address incentive) external; function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: MIT // !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !! pragma solidity ^0.8.3; interface ICurveFactory { event BasePoolAdded(address base_pool, address implementat); event MetaPoolDeployed( address coin, address base_pool, uint256 A, uint256 fee, address deployer ); function find_pool_for_coins(address _from, address _to) external view returns (address); function find_pool_for_coins( address _from, address _to, uint256 i ) external view returns (address); function get_n_coins(address _pool) external view returns (uint256, uint256); function get_coins(address _pool) external view returns (address[2] memory); function get_underlying_coins(address _pool) external view returns (address[8] memory); function get_decimals(address _pool) external view returns (uint256[2] memory); function get_underlying_decimals(address _pool) external view returns (uint256[8] memory); function get_rates(address _pool) external view returns (uint256[2] memory); function get_balances(address _pool) external view returns (uint256[2] memory); function get_underlying_balances(address _pool) external view returns (uint256[8] memory); function get_A(address _pool) external view returns (uint256); function get_fees(address _pool) external view returns (uint256, uint256); function get_admin_balances(address _pool) external view returns (uint256[2] memory); function get_coin_indices( address _pool, address _from, address _to ) external view returns ( int128, int128, bool ); function add_base_pool( address _base_pool, address _metapool_implementation, address _fee_receiver ) external; function deploy_metapool( address _base_pool, string memory _name, string memory _symbol, address _coin, uint256 _A, uint256 _fee ) external returns (address); function commit_transfer_ownership(address addr) external; function accept_transfer_ownership() external; function set_fee_receiver(address _base_pool, address _fee_receiver) external; function convert_fees() external returns (bool); function admin() external view returns (address); function future_admin() external view returns (address); function pool_list(uint256 arg0) external view returns (address); function pool_count() external view returns (uint256); function base_pool_list(uint256 arg0) external view returns (address); function base_pool_count() external view returns (uint256); function fee_receiver(address arg0) external view returns (address); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "./interfaces/IMetaPool.sol"; contract TWAPOracle { address public immutable pool; address public immutable token0; address public immutable token1; uint256 public price0Average; uint256 public price1Average; uint256 public pricesBlockTimestampLast; uint256[2] public priceCumulativeLast; constructor( address _pool, address _uADtoken0, address _curve3CRVtoken1 ) { pool = _pool; // coin at index 0 is uAD and index 1 is 3CRV require( IMetaPool(_pool).coins(0) == _uADtoken0 && IMetaPool(_pool).coins(1) == _curve3CRVtoken1, "TWAPOracle: COIN_ORDER_MISMATCH" ); token0 = _uADtoken0; token1 = _curve3CRVtoken1; uint256 _reserve0 = uint112(IMetaPool(_pool).balances(0)); uint256 _reserve1 = uint112(IMetaPool(_pool).balances(1)); // ensure that there's liquidity in the pair require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES"); // ensure that pair balance is perfect require(_reserve0 == _reserve1, "TWAPOracle: PAIR_UNBALANCED"); priceCumulativeLast = IMetaPool(_pool).get_price_cumulative_last(); pricesBlockTimestampLast = IMetaPool(_pool).block_timestamp_last(); price0Average = 1 ether; price1Average = 1 ether; } // calculate average price function update() external { (uint256[2] memory priceCumulative, uint256 blockTimestamp) = _currentCumulativePrices(); if (blockTimestamp - pricesBlockTimestampLast > 0) { // get the balances between now and the last price cumulative snapshot uint256[2] memory twapBalances = IMetaPool(pool).get_twap_balances( priceCumulativeLast, priceCumulative, blockTimestamp - pricesBlockTimestampLast ); // price to exchange amounIn uAD to 3CRV based on TWAP price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances); // price to exchange amounIn 3CRV to uAD based on TWAP price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances); // we update the priceCumulative priceCumulativeLast = priceCumulative; pricesBlockTimestampLast = blockTimestamp; } } // note this will always return 0 before update has been called successfully // for the first time. function consult(address token) external view returns (uint256 amountOut) { if (token == token0) { // price to exchange 1 uAD to 3CRV based on TWAP amountOut = price0Average; } else { require(token == token1, "TWAPOracle: INVALID_TOKEN"); // price to exchange 1 3CRV to uAD based on TWAP amountOut = price1Average; } } function _currentCumulativePrices() internal view returns (uint256[2] memory priceCumulative, uint256 blockTimestamp) { priceCumulative = IMetaPool(pool).get_price_cumulative_last(); blockTimestamp = IMetaPool(pool).block_timestamp_last(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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; 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); } pragma solidity >=0.5.0; 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; }
convert to curve LP amount to convert to curve LP by swapping to 3CRV and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens the LP token are sent to the bonding contract we need to approve metaPool swap amount of uAD => 3CRV approve metapool to transfer our 3CRV deposit liquidity update TWAP price
function _convertToCurveLPAndTransfer(uint256 amount) internal returns (uint256) { IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount ); uint256 amount3CRVReceived = IMetaPool(manager.stableSwapMetaPoolAddress()).exchange( 0, 1, amount, 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount3CRVReceived ); uint256 res = IMetaPool(manager.stableSwapMetaPoolAddress()).add_liquidity( [0, amount3CRVReceived], 0, manager.bondingContractAddress() ); return res; }
11,722,337
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } library SupportStructs { struct CalcMaxDebtLocalVars { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 totalDebt; uint256 utilizationRate; uint256 totalLiquidity; uint256 targetUtilizationRate; uint256 maxProtocolDebt; } struct IrsVars { uint256 optimalRate; uint256 baseRate; uint256 slope1; uint256 slope2; } } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IAaveIncentivesController interface IAaveIncentivesController { /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); function getDistributionEnd() external view returns (uint256); function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); } // Part: ILendingPoolAddressesProvider /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // Part: IOptionalERC20 interface IOptionalERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // Part: IPriceOracle interface IPriceOracle { function getAssetPrice(address _asset) external view returns (uint256); function getAssetsPrices(address[] calldata _assets) external view returns (uint256[] memory); function getSourceOfAsset(address _asset) external view returns (address); function getFallbackOracle() external view returns (address); } // Part: IReserveInterestRateStrategy /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function OPTIMAL_UTILIZATION_RATE() external view returns (uint256); function EXCESS_UTILIZATION_RATE() external view returns (uint256); function variableRateSlope1() external view returns (uint256); function variableRateSlope2() external view returns (uint256); function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 utilizationRate, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // Part: IScaledBalanceToken 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); } // Part: IStakedAave interface IStakedAave { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function getTotalRewardsBalance(address) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function stakersCooldowns(address) external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // Part: ISwap interface ISwap { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: WadRayMath /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a); return result; } } // Part: ILendingPool interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw( address indexed reserve, address indexed user, address indexed to, uint256 amount ); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled( address indexed reserve, address indexed user ); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled( address indexed reserve, address indexed user ); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate( address indexed reserve, address indexed user ); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress( address reserve, address rateStrategyAddress ) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // Part: IProtocolDataProvider interface IProtocolDataProvider { struct TokenData { string symbol; address tokenAddress; } function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } // Part: IVariableDebtToken /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IERC20, IScaledBalanceToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint( address indexed from, address indexed onBehalfOf, uint256 value, uint256 index ); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // Part: IVault interface IVault is IERC20 { function token() external view returns (address); function decimals() external view returns (uint256); function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function withdraw( uint256 amount, address account, uint256 maxLoss ) external returns (uint256); function availableDepositLimit() external view returns (uint256); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: IInitializableAToken /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.5"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: IAToken interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn( address indexed from, address indexed target, uint256 value, uint256 index ); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer( address indexed from, address indexed to, uint256 value, uint256 index ); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // File: Strategy.sol contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using WadRayMath for uint256; bool internal isOriginal = true; // max interest rate we can afford to pay for borrowing investment token // amount in Ray (1e27 = 100%) uint256 public acceptableCostsRay = 1e27; // max amount to borrow. used to manually limit amount (for yVault to keep APY) uint256 public maxTotalBorrowIT; bool public isWantIncentivised; bool public isInvestmentTokenIncentivised; // if set to true, the strategy will not try to repay debt by selling want bool public leaveDebtBehind; // Aave's referral code uint16 internal referral; // NOTE: LTV = Loan-To-Value = debt/collateral // Target LTV: ratio up to which which we will borrow uint16 public targetLTVMultiplier = 6_000; // Warning LTV: ratio at which we will repay uint16 public warningLTVMultiplier = 8_000; // 80% of liquidation LTV // support uint16 internal constant MAX_BPS = 10_000; // 100% uint16 internal constant MAX_MULTIPLIER = 9_000; // 90% IAToken internal aToken; IVariableDebtToken internal variableDebtToken; IVault public yVault; IERC20 internal investmentToken; ISwap internal constant router = ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IStakedAave internal constant stkAave = IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5); IProtocolDataProvider internal constant protocolDataProvider = IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant AAVE = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9; uint256 internal minThreshold; uint256 public maxLoss; string internal strategyName; constructor( address _vault, address _yVault, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, string memory _strategyName ) public BaseStrategy(_vault) { _initializeThis( _yVault, _isWantIncentivised, _isInvestmentTokenIncentivised, _strategyName ); } // ----------------- PUBLIC VIEW FUNCTIONS ----------------- function name() external view override returns (string memory) { return strategyName; } function estimatedTotalAssets() public view override returns (uint256) { // not taking into account aave rewards (they are staked and not accesible) return balanceOfWant() // balance of want .add(balanceOfAToken()) // asset suplied as collateral .add( _fromETH( _toETH(_valueOfInvestment(), address(investmentToken)), address(want) ) ) // current value of assets deposited in vault .sub( _fromETH( _toETH(balanceOfDebt(), address(investmentToken)), address(want) ) ); // liabilities } // ----------------- SETTERS ----------------- // we put all together to save contract bytecode (!) function setStrategyParams( uint16 _targetLTVMultiplier, uint16 _warningLTVMultiplier, uint256 _acceptableCostsRay, uint16 _aaveReferral, uint256 _maxTotalBorrowIT, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, bool _leaveDebtBehind, uint256 _maxLoss ) external onlyAuthorized { require( _warningLTVMultiplier <= MAX_MULTIPLIER && _targetLTVMultiplier <= _warningLTVMultiplier ); targetLTVMultiplier = _targetLTVMultiplier; warningLTVMultiplier = _warningLTVMultiplier; acceptableCostsRay = _acceptableCostsRay; maxTotalBorrowIT = _maxTotalBorrowIT; referral = _aaveReferral; isWantIncentivised = _isWantIncentivised; isInvestmentTokenIncentivised = _isInvestmentTokenIncentivised; leaveDebtBehind = _leaveDebtBehind; require(maxLoss <= 10_000); maxLoss = _maxLoss; } event Cloned(address indexed clone); function cloneAaveLenderBorrower( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, string memory _strategyName ) external returns (address newStrategy) { require(isOriginal); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _yVault, _isWantIncentivised, _isInvestmentTokenIncentivised, _strategyName ); emit Cloned(newStrategy); } function _initializeThis( address _yVault, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, string memory _strategyName ) internal { minReportDelay = 24 * 3600; maxReportDelay = 10 * 24 * 3600; profitFactor = 100; // debtThreshold = 0; It's 0 by default. yVault = IVault(_yVault); investmentToken = IERC20(IVault(_yVault).token()); (address _aToken, , ) = protocolDataProvider.getReserveTokensAddresses(address(want)); aToken = IAToken(_aToken); (, , address _variableDebtToken) = protocolDataProvider.getReserveTokensAddresses( address(investmentToken) ); variableDebtToken = IVariableDebtToken(_variableDebtToken); minThreshold = (10**(yVault.decimals())).div(100); // 0.01 minThreshold isWantIncentivised = _isWantIncentivised; isInvestmentTokenIncentivised = _isInvestmentTokenIncentivised; maxTotalBorrowIT = type(uint256).max; // set to max to avoid limits. this may trigger revert in some parts if not correctly handled maxLoss = 1; strategyName = _strategyName; } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, bool _isWantIncentivised, bool _isInvestmentTokenIncentivised, string memory _strategyName ) public { _initialize(_vault, _strategist, _rewards, _keeper); require(address(yVault) == address(0)); _initializeThis( _yVault, _isWantIncentivised, _isInvestmentTokenIncentivised, _strategyName ); } // ----------------- MAIN STRATEGY FUNCTIONS ----------------- function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 balanceInit = balanceOfWant(); // claim rewards from Aave's Liquidity Mining Program _claimRewards(); // claim rewards from yVault _takeVaultProfit(); // claim interest from lending _takeLendingProfit(); uint256 balanceOfWant = balanceOfWant(); if (balanceOfWant > balanceInit) { _profit = balanceOfWant.sub(balanceInit); } // if the vault is claiming repayment of debt if (_debtOutstanding > 0) { uint256 _amountFreed = 0; (_amountFreed, _loss) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > 0) { _profit = 0; } } } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 wantBalance = balanceOfWant(); // if we have enough want to deposit more into Aave, we do // NOTE: we do not skip the rest of the function if we don't as it may need to repay or take on more debt if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToAave(amountToDeposit); } // NOTE: debt + collateral calcs are done in ETH ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); // if there is no want deposited into aave, don't do nothing // this means no debt is borrowed from aave too if (totalCollateralETH == 0) { return; } uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH); uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); // 60% under liquidation Threshold uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); // 80% under liquidation Threshold // decide in which range we are and act accordingly: // SUBOPTIMAL(borrow) (e.g. from 0 to 60% liqLTV) // HEALTHY(do nothing) (e.g. from 60% to 80% liqLTV) // UNHEALTHY(repay) (e.g. from 80% to 100% liqLTV) // we use our target cost of capital to calculate how much debt we can take on / how much debt we need to repay // in order to bring costs back to an acceptable range // currentProtocolDebt => total amount of debt taken by all Aave's borrowers // maxProtocolDebt => amount of total debt at which the cost of capital is equal to our acceptable costs // if the current protocol debt is higher than the max protocol debt, we will repay debt (uint256 currentProtocolDebt, uint256 maxProtocolDebt) = _calculateMaxDebt(); if (targetLTV > currentLTV && currentProtocolDebt < maxProtocolDebt) { // SUBOPTIMAL RATIO: our current Loan-to-Value is lower than what we want // AND costs are lower than our max acceptable costs // we need to take on more debt uint256 targetDebtETH = totalCollateralETH.mul(targetLTV).div(MAX_BPS); uint256 amountToBorrowETH = targetDebtETH.sub(totalDebtETH); // safe bc we checked ratios amountToBorrowETH = Math.min( availableBorrowsETH, amountToBorrowETH ); // cap the amount of debt we are taking according to our acceptable costs // if with the new loan we are increasing our cost of capital over what is healthy if (currentProtocolDebt.add(amountToBorrowETH) > maxProtocolDebt) { // Can't underflow because it's checked in the previous if condition amountToBorrowETH = maxProtocolDebt.sub(currentProtocolDebt); } uint256 maxTotalBorrowETH = _toETH(maxTotalBorrowIT, address(investmentToken)); if (totalDebtETH.add(amountToBorrowETH) > maxTotalBorrowETH) { amountToBorrowETH = maxTotalBorrowETH > totalDebtETH ? maxTotalBorrowETH.sub(totalDebtETH) : 0; } // convert to InvestmentToken uint256 amountToBorrowIT = _fromETH(amountToBorrowETH, address(investmentToken)); if (amountToBorrowIT > 0) { _lendingPool().borrow( address(investmentToken), amountToBorrowIT, 2, referral, address(this) ); } _depositInYVault(); } else if ( currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt ) { // UNHEALTHY RATIO // we may be in this case if the current cost of capital is higher than our max cost of capital // we repay debt to set it to targetLTV uint256 targetDebtETH = targetLTV.mul(totalCollateralETH).div(MAX_BPS); uint256 amountToRepayETH = targetDebtETH < totalDebtETH ? totalDebtETH.sub(targetDebtETH) : 0; if (maxProtocolDebt == 0) { amountToRepayETH = totalDebtETH; } else if (currentProtocolDebt > maxProtocolDebt) { amountToRepayETH = Math.max( amountToRepayETH, currentProtocolDebt.sub(maxProtocolDebt) ); } uint256 amountToRepayIT = _fromETH(amountToRepayETH, address(investmentToken)); uint256 withdrawnIT = _withdrawFromYVault(amountToRepayIT); // we withdraw from investmentToken vault _repayInvestmentTokenDebt(withdrawnIT); // we repay the investmentToken debt with Aave } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); // if we have enough want to take care of the liquidatePosition without actually liquidating positons if (balance >= _amountNeeded) { return (_amountNeeded, 0); } // NOTE: amountNeeded is in want // NOTE: repayment amount is in investmentToken // NOTE: collateral and debt calcs are done in ETH (always, see Aave docs) // We first repay whatever we need to repay to keep healthy ratios uint256 amountToRepayIT = _calculateAmountToRepay(_amountNeeded); uint256 withdrawnIT = _withdrawFromYVault(amountToRepayIT); // we withdraw from investmentToken vault _repayInvestmentTokenDebt(withdrawnIT); // we repay the investmentToken debt with Aave // it will return the free amount of want _withdrawWantFromAave(_amountNeeded); balance = balanceOfWant(); // we check if we withdrew less than expected AND should buy investmentToken with want (realising losses) if ( _amountNeeded > balance && balanceOfDebt() > 0 && // still some debt remaining balanceOfInvestmentToken().add(_valueOfInvestment()) == 0 && // but no capital to repay !leaveDebtBehind // if set to true, the strategy will not try to repay debt by selling want ) { // using this part of code will result in losses but it is necessary to unlock full collateral in case of wind down // we calculate how much want we need to fulfill the want request uint256 remainingAmountWant = _amountNeeded.sub(balance); // then calculate how much InvestmentToken we need to unlock collateral amountToRepayIT = _calculateAmountToRepay(remainingAmountWant); // we buy investmentToken with Want _buyInvestmentTokenWithWant(amountToRepayIT); // we repay debt to actually unlock collateral // after this, balanceOfDebt should be 0 _repayInvestmentTokenDebt(amountToRepayIT); // then we try withdraw once more _withdrawWantFromAave(remainingAmountWant); } uint256 totalAssets = balanceOfWant(); if (_amountNeeded > totalAssets) { _liquidatedAmount = totalAssets; _loss = _amountNeeded.sub(totalAssets); } else { _liquidatedAmount = _amountNeeded; } } function delegatedAssets() external view override returns (uint256) { // returns total debt borrowed in want (which is the delegatedAssets) return _fromETH( _toETH(balanceOfDebt(), address(investmentToken)), address(want) ); } function prepareMigration(address _newStrategy) internal override { // nothing to do since debt cannot be migrated } function harvestTrigger(uint256 callCost) public view override returns (bool) { // we harvest if: // 1. stakedAave is ready to be converted to Aave and sold return _checkCooldown() || super.harvestTrigger(_fromETH(callCost, address(want))); } function tendTrigger(uint256 callCost) public view override returns (bool) { // we adjust position if: // 1. LTV ratios are not in the HEALTHY range (either we take on more debt or repay debt) // 2. costs are not acceptable and we need to repay debt ( uint256 totalCollateralETH, uint256 totalDebtETH, , uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH); uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); (uint256 currentProtocolDebt, uint256 maxProtocolDebt) = _calculateMaxDebt(); if ( (currentLTV < targetLTV && currentProtocolDebt < maxProtocolDebt && targetLTV.sub(currentLTV) > 100) || // WE NEED TO TAKE ON MORE DEBT (currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt) // WE NEED TO REPAY DEBT BECAUSE OF UNHEALTHY RATIO OR BORROWING COSTS ) { return true; } // no call to super.tendTrigger as it would return false return false; } // ----------------- INTERNAL FUNCTIONS SUPPORT ----------------- function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } // no need to check allowance bc the contract == token uint256 balancePrior = balanceOfInvestmentToken(); uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } // we cannot pay more than loose balance uint256 balance = balanceOfInvestmentToken(); amount = Math.min(amount, balance); // we cannot pay more than we owe amount = Math.min(balanceOfDebt(), amount); _checkAllowance( address(_lendingPool()), address(investmentToken), amount ); if (amount > 0) { _lendingPool().repay( address(investmentToken), amount, uint256(2), address(this) ); } } function _depositInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _claimRewards() internal { if (isInvestmentTokenIncentivised || isWantIncentivised) { // redeem AAVE from stkAave uint256 stkAaveBalance = IERC20(address(stkAave)).balanceOf(address(this)); if (stkAaveBalance > 0 && _checkCooldown()) { stkAave.redeem(address(this), stkAaveBalance); } // claim AAVE rewards stkAave.claimRewards(address(this), type(uint256).max); // sell AAVE for want // a minimum balance of 0.01 AAVE is required uint256 aaveBalance = IERC20(AAVE).balanceOf(address(this)); if (aaveBalance > 1e15) { _sellAAVEForWant(aaveBalance); } // claim rewards // only add to assets those assets that are incentivised address[] memory assets; if (isInvestmentTokenIncentivised && isWantIncentivised) { assets = new address[](2); assets[0] = address(aToken); assets[1] = address(variableDebtToken); } else if (isInvestmentTokenIncentivised) { assets = new address[](1); assets[0] = address(variableDebtToken); } else if (isWantIncentivised) { assets = new address[](1); assets[0] = address(aToken); } _incentivesController().claimRewards( assets, type(uint256).max, address(this) ); // request start of cooldown period if (IERC20(address(stkAave)).balanceOf(address(this)) > 0) { stkAave.cooldown(); } } } function _takeLendingProfit() internal { uint256 depositedWant = vault.strategies(address(this)).totalDebt; uint256 currentWantInAave = balanceOfAToken(); if (currentWantInAave > depositedWant) { uint256 toWithdraw = currentWantInAave.sub(depositedWant); _withdrawWantFromAave(toWithdraw); } } //withdraw an amount including any want balance function _withdrawWantFromAave(uint256 amount) internal { uint256 balanceUnderlying = balanceOfAToken(); if (amount > balanceUnderlying) { amount = balanceUnderlying; } uint256 maxWithdrawal = Math.min(_maxWithdrawal(), want.balanceOf(address(aToken))); uint256 toWithdraw = Math.min(amount, maxWithdrawal); if (toWithdraw > 0) { _checkAllowance( address(_lendingPool()), address(aToken), toWithdraw ); _lendingPool().withdraw(address(want), toWithdraw, address(this)); } } function _maxWithdrawal() internal view returns (uint256) { (uint256 totalCollateralETH, uint256 totalDebtETH, , , uint256 ltv, ) = _getAaveUserAccountData(); uint256 minCollateralETH = ltv > 0 ? totalDebtETH.mul(MAX_BPS).div(ltv) : totalCollateralETH; if (minCollateralETH > totalCollateralETH) { return 0; } return _fromETH(totalCollateralETH.sub(minCollateralETH), address(want)); } function _calculateAmountToRepay(uint256 amount) internal view returns (uint256) { if (amount == 0) { return 0; } // we check if the collateral that we are withdrawing leaves us in a risky range, we then take action ( uint256 totalCollateralETH, uint256 totalDebtETH, , uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); uint256 amountToWithdrawETH = _toETH(amount, address(want)); // calculate the collateral that we are leaving after withdrawing uint256 newCollateral = totalCollateralETH > amountToWithdrawETH ? totalCollateralETH.sub(amountToWithdrawETH) : 0; uint256 ltvAfterWithdrawal = newCollateral > 0 ? totalDebtETH.mul(MAX_BPS).div(newCollateral) : type(uint256).max; // check if the new LTV is in UNHEALTHY range // remember that if balance > _amountNeeded, ltvAfterWithdrawal == 0 (0 risk) // this is not true but the effect will be the same uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); if (ltvAfterWithdrawal <= warningLTV) { // no need of repaying debt because the LTV is ok return 0; } else if (ltvAfterWithdrawal == type(uint256).max) { // we are withdrawing 100% of collateral so we need to repay full debt return _fromETH(totalDebtETH, address(investmentToken)); } uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); // WARNING: this only works for a single collateral asset, otherwise liquidationThreshold might change depending on the collateral being withdrawn // e.g. we have USDC + WBTC as collateral, end liquidationThreshold will be different depending on which asset we withdraw uint256 newTargetDebt = targetLTV.mul(newCollateral).div(MAX_BPS); // if newTargetDebt is higher, we don't need to repay anything if (newTargetDebt > totalDebtETH) { return 0; } return _fromETH( totalDebtETH.sub(newTargetDebt) < minThreshold ? totalDebtETH : totalDebtETH.sub(newTargetDebt), address(investmentToken) ); } function _depositToAave(uint256 amount) internal { if (amount == 0) { return; } ILendingPool lp = _lendingPool(); _checkAllowance(address(lp), address(want), amount); lp.deposit(address(want), amount, address(this), referral); } function _checkCooldown() internal view returns (bool) { if (!isWantIncentivised && !isInvestmentTokenIncentivised) { return false; } uint256 cooldownStartTimestamp = IStakedAave(stkAave).stakersCooldowns(address(this)); uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS(); uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW(); if (block.timestamp >= cooldownStartTimestamp.add(COOLDOWN_SECONDS)) { return block.timestamp.sub( cooldownStartTimestamp.add(COOLDOWN_SECONDS) ) <= UNSTAKE_WINDOW || cooldownStartTimestamp == 0; } return false; } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellInvestmentForWant(balanceOfInvestmentToken()); } } // ----------------- INTERNAL CALCS ----------------- function _calculateMaxDebt() internal view returns (uint256 currentProtocolDebt, uint256 maxProtocolDebt) { // This function is used to calculate the maximum amount of debt that the protocol can take // to keep the cost of capital lower than the set acceptableCosts // This maxProtocolDebt will be used to decide if capital costs are acceptable or not // and to repay required debt to keep the rates below acceptable costs // Hack to avoid the stack too deep compiler error. SupportStructs.CalcMaxDebtLocalVars memory vars; DataTypes.ReserveData memory reserveData = _lendingPool().getReserveData(address(investmentToken)); IReserveInterestRateStrategy irs = IReserveInterestRateStrategy( reserveData.interestRateStrategyAddress ); ( vars.availableLiquidity, // = total supply - total stable debt - total variable debt vars.totalStableDebt, // total debt paying stable interest rates vars.totalVariableDebt, // total debt paying stable variable rates , , , , , , ) = protocolDataProvider.getReserveData(address(investmentToken)); vars.totalDebt = vars.totalStableDebt.add(vars.totalVariableDebt); vars.totalLiquidity = vars.availableLiquidity.add(vars.totalDebt); vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(vars.totalLiquidity); // Aave's Interest Rate Strategy Parameters (see docs) SupportStructs.IrsVars memory irsVars; irsVars.optimalRate = irs.OPTIMAL_UTILIZATION_RATE(); irsVars.baseRate = irs.baseVariableBorrowRate(); // minimum cost of capital with 0 % of utilisation rate irsVars.slope1 = irs.variableRateSlope1(); // rate of increase of cost of debt up to Optimal Utilisation Rate irsVars.slope2 = irs.variableRateSlope2(); // rate of increase of cost of debt above Optimal Utilisation Rate // acceptableCosts should always be > baseVariableBorrowRate // If it's not this will revert since the strategist set the wrong // acceptableCosts value if ( vars.utilizationRate < irsVars.optimalRate && acceptableCostsRay < irsVars.baseRate.add(irsVars.slope1) ) { // we solve Aave's Interest Rates equation for sub optimal utilisation rates // IR = BASERATE + SLOPE1 * CURRENT_UTIL_RATE / OPTIMAL_UTIL_RATE vars.targetUtilizationRate = ( acceptableCostsRay.sub(irsVars.baseRate) ) .rayMul(irsVars.optimalRate) .rayDiv(irsVars.slope1); } else { // Special case where protocol is above utilization rate but we want // a lower interest rate than (base + slope1) if (acceptableCostsRay < irsVars.baseRate.add(irsVars.slope1)) { return (_toETH(vars.totalDebt, address(investmentToken)), 0); } // we solve Aave's Interest Rates equation for utilisation rates above optimal U // IR = BASERATE + SLOPE1 + SLOPE2 * (CURRENT_UTIL_RATE - OPTIMAL_UTIL_RATE) / (1-OPTIMAL_UTIL_RATE) vars.targetUtilizationRate = ( acceptableCostsRay.sub(irsVars.baseRate.add(irsVars.slope1)) ) .rayMul(uint256(1e27).sub(irsVars.optimalRate)) .rayDiv(irsVars.slope2) .add(irsVars.optimalRate); } vars.maxProtocolDebt = vars .totalLiquidity .rayMul(vars.targetUtilizationRate) .rayDiv(1e27); return ( _toETH(vars.totalDebt, address(investmentToken)), _toETH(vars.maxProtocolDebt, address(investmentToken)) ); } function balanceOfWant() internal view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() internal view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfAToken() internal view returns (uint256) { return aToken.balanceOf(address(this)); } function balanceOfDebt() internal view returns (uint256) { return variableDebtToken.balanceOf(address(this)); } function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _getAaveUserAccountData() internal view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { return _lendingPool().getUserAccountData(address(this)); } function _getTargetLTV(uint256 liquidationThreshold) internal view returns (uint256) { return liquidationThreshold.mul(uint256(targetLTVMultiplier)).div(MAX_BPS); } function _getWarningLTV(uint256 liquidationThreshold) internal view returns (uint256) { return liquidationThreshold.mul(uint256(warningLTVMultiplier)).div( MAX_BPS ); } // ----------------- TOKEN CONVERSIONS ----------------- function getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(WETH); _path[2] = _token_out; } } function _sellAAVEForWant(uint256 _amount) internal { if (_amount == 0) { return; } _checkAllowance(address(router), address(AAVE), _amount); router.swapExactTokensForTokens( _amount, 0, getTokenOutPath(address(AAVE), address(want)), address(this), now ); } function _sellInvestmentForWant(uint256 _amount) internal { if (_amount == 0) { return; } // NOTE: 1:1 if (address(want) == address(investmentToken)) { return; } _checkAllowance(address(router), address(investmentToken), _amount); router.swapExactTokensForTokens( _amount, 0, getTokenOutPath(address(investmentToken), address(want)), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0) { return; } if (address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } function _toETH(uint256 _amount, address asset) internal view returns (uint256) { if ( _amount == 0 || _amount == type(uint256).max || address(asset) == address(WETH) // 1:1 change ) { return _amount; } return _amount.mul(_priceOracle().getAssetPrice(asset)).div( uint256(10)**uint256(IOptionalERC20(asset).decimals()) ); } function _fromETH(uint256 _amount, address asset) internal view returns (uint256) { if ( _amount == 0 || _amount == type(uint256).max || address(asset) == address(WETH) // 1:1 change ) { return _amount; } return _amount .mul(uint256(10)**uint256(IOptionalERC20(asset).decimals())) .div(_priceOracle().getAssetPrice(asset)); } // ----------------- INTERNAL SUPPORT GETTERS ----------------- function _lendingPool() internal view returns (ILendingPool lendingPool) { lendingPool = ILendingPool( protocolDataProvider.ADDRESSES_PROVIDER().getLendingPool() ); } function _priceOracle() internal view returns (IPriceOracle) { return IPriceOracle( protocolDataProvider.ADDRESSES_PROVIDER().getPriceOracle() ); } function _incentivesController() internal view returns (IAaveIncentivesController) { if (isWantIncentivised) { return aToken.getIncentivesController(); } else if (isInvestmentTokenIncentivised) { return variableDebtToken.getIncentivesController(); } else { return IAaveIncentivesController(0); } } function protectedTokens() internal view override returns (address[] memory) {} }
if we have enough want to deposit more into Aave, we do NOTE: we do not skip the rest of the function if we don't as it may need to repay or take on more debt if there is no want deposited into aave, don't do nothing this means no debt is borrowed from aave too SUBOPTIMAL RATIO: our current Loan-to-Value is lower than what we want AND costs are lower than our max acceptable costs we need to take on more debt cap the amount of debt we are taking according to our acceptable costs if with the new loan we are increasing our cost of capital over what is healthy Can't underflow because it's checked in the previous if condition UNHEALTHY RATIO we may be in this case if the current cost of capital is higher than our max cost of capital we repay debt to set it to targetLTV
function adjustPosition(uint256 _debtOutstanding) internal override { uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToAave(amountToDeposit); } uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, , ) = _getAaveUserAccountData(); if (totalCollateralETH == 0) { return; } uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH); _calculateMaxDebt(); if (targetLTV > currentLTV && currentProtocolDebt < maxProtocolDebt) { uint256 targetDebtETH = totalCollateralETH.mul(targetLTV).div(MAX_BPS); amountToBorrowETH = Math.min( availableBorrowsETH, amountToBorrowETH ); if (currentProtocolDebt.add(amountToBorrowETH) > maxProtocolDebt) { amountToBorrowETH = maxProtocolDebt.sub(currentProtocolDebt); } uint256 maxTotalBorrowETH = _toETH(maxTotalBorrowIT, address(investmentToken)); if (totalDebtETH.add(amountToBorrowETH) > maxTotalBorrowETH) { amountToBorrowETH = maxTotalBorrowETH > totalDebtETH ? maxTotalBorrowETH.sub(totalDebtETH) : 0; } _fromETH(amountToBorrowETH, address(investmentToken)); if (amountToBorrowIT > 0) { _lendingPool().borrow( address(investmentToken), amountToBorrowIT, 2, referral, address(this) ); } _depositInYVault(); } else if ( currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt ) { uint256 targetDebtETH = targetLTV.mul(totalCollateralETH).div(MAX_BPS); uint256 amountToRepayETH = targetDebtETH < totalDebtETH ? totalDebtETH.sub(targetDebtETH) : 0; if (maxProtocolDebt == 0) { amountToRepayETH = totalDebtETH; amountToRepayETH = Math.max( amountToRepayETH, currentProtocolDebt.sub(maxProtocolDebt) ); } uint256 amountToRepayIT = _fromETH(amountToRepayETH, address(investmentToken)); } }
186,529
contract MultiSigERC20Token { uint constant public MAX_OWNER_COUNT = 50; // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; uint256 public totalSupply; address[] public owners; // Variables for multisig uint256 public required; uint public transactionCount; // Events event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId,string operation, address source, address destination, uint256 value, string reason); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); // Mappings mapping (uint => MetaTransaction) public transactions; mapping (address => uint256) public withdrawalLimit; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; mapping (address => bool) public frozenAccount; mapping (address => uint256) public balanceOf; // Meta data for pending and executed Transactions struct MetaTransaction { address source; address destination; uint value; bool executed; uint operation; string reason; } // Modifiers modifier ownerDoesNotExist(address owner) { require (!isOwner[owner]); _; } modifier ownerExists(address owner) { require (isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require (transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require (confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require (!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require (!transactions[transactionId].executed); _; } modifier notNull(address _address) { require (_address != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable public { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } /** * Constrctor function * * Initializes contract with initial supply tokens to the contract and sets owner to the * creator of the contract */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[this] = totalSupply; // Give the contract all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes isOwner[msg.sender] = true; // Set Owner to Contract Creator required = 1; owners.push(msg.sender); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check if the sender is frozen require(!frozenAccount[_from]); // Check if the recipient is frozen require(!frozenAccount[_to]); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) internal { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) internal ownerDoesNotExist(owner) notNull(owner) { isOwner[owner] = true; owners.push(owner); required = required + 1; emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) internal ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) internal ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint256 _required) internal { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function submitTransaction(address source, address destination, uint256 value, uint operation, string reason) public returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = MetaTransaction({ source: source, destination: destination, value: value, operation: operation, executed: false, reason: reason }); transactionCount += 1; if(operation == 1) // Operation 1 is Add Owner { emit Submission(transactionId,"Add Owner", source, destination, value, reason); } else if(operation == 2) // Operation 2 is Remove Owner { emit Submission(transactionId,"Remove Owner", source, destination, value, reason); } else if(operation == 3) // Operation 3 is Replace Owner { emit Submission(transactionId,"Replace Owner", source, destination, value, reason); } else if(operation == 4) // Operation 4 is Freeze Account { emit Submission(transactionId,"Freeze Account", source, destination, value, reason); } else if(operation == 5) // Operation 5 is UnFreeze Account { emit Submission(transactionId,"UnFreeze Account", source, destination, value, reason); } else if(operation == 6) // Operation 6 is change rquirement { emit Submission(transactionId,"Change Requirement", source, destination, value, reason); } else if(operation == 7) // Operation 7 is Issue Tokens from Contract { emit Submission(transactionId,"Issue Tokens", source, destination, value, reason); } else if(operation == 8) // Operation 8 is Admin Transfer Tokens { emit Submission(transactionId,"Admin Transfer Tokens", source, destination, value, reason); } else if(operation == 9) // Operation 9 is Set Owners Unsigned Withdrawal Limit { emit Submission(transactionId,"Set Unsigned Ethereum Withdrawal Limit", source, destination, value, reason); } else if(operation == 10) // Operation 10 is Admin Withdraw Ether without multisig { emit Submission(transactionId,"Unsigned Ethereum Withdrawal", source, destination, value, reason); } else if(operation == 11) // Operation 11 is Admin Withdraw Ether with multisig { emit Submission(transactionId,"Withdraw Ethereum", source, destination, value, reason); } } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { MetaTransaction storage transaction = transactions[transactionId]; if(transaction.operation == 1) // Operation 1 is Add Owner { addOwner(transaction.destination); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 2) // Operation 2 is Remove Owner { removeOwner(transaction.destination); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 3) // Operation 3 is Replace Owner { replaceOwner(transaction.source,transaction.destination); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 4) // Operation 4 is Freeze Account { freezeAccount(transaction.destination,true); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 5) // Operation 5 is UnFreeze Account { freezeAccount(transaction.destination, false); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 6) // Operation 6 is UnFreeze Account { changeRequirement(transaction.value); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 7) // Operation 7 is Issue Tokens from Contract { _transfer(this,transaction.destination,transaction.value); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 8) // Operation 8 is Admin Transfer Tokens { _transfer(transaction.source,transaction.destination,transaction.value); transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 9) // Operation 9 is Set Owners Unsigned Withdrawal Limit { require(isOwner[transaction.destination]); withdrawalLimit[transaction.destination] = transaction.value; transaction.executed = true; emit Execution(transactionId); } else if(transaction.operation == 11) // Operation 11 is Admin Withdraw Ether with multisig { require(isOwner[transaction.destination]); transaction.destination.transfer(transaction.value); transaction.executed = true; emit Execution(transactionId); } } else if(transaction.operation == 10) // Operation 10 is Admin Withdraw Ether without multisig { require(isOwner[transaction.destination]); require(withdrawalLimit[transaction.destination] <= transaction.value); withdrawalLimit[transaction.destination] -= transaction.value; assert(withdrawalLimit[transaction.destination] > 0); transaction.destination.transfer(transaction.value); transaction.executed = true; emit Execution(transactionId); } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Allows to add a new owner. Transaction has to be sent by wallet. owner Address of new owner.
function addOwner(address owner) internal ownerDoesNotExist(owner) notNull(owner) { isOwner[owner] = true; owners.push(owner); required = required + 1; emit OwnerAddition(owner); }
7,241,500
./partial_match/1/0xB4a79ec84FE92E4B9987dC8746b8f6eA671fbAD8/sources/LayerX.sol
generate the uniswap pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = _router.WETH(); _approve(address(this), address(_router), tokenAmount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, block.timestamp ); }
15,922,972
// 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); } } } } 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); } pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.8.0; /** * @dev A token holder contract that will allow a beneficiary to extract the * tokens after a given release time. * * Useful for simple vesting schedules like "advisors get all of their tokens * after 1 year". */ contract TokenTimelock { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private immutable _token; // beneficiary of tokens after they are released address private immutable _beneficiary; // timestamp when token release is enabled uint256 private immutable _releaseTime; constructor( IERC20 token_, address beneficiary_, uint256 releaseTime_ ) { require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time"); _token = token_; _beneficiary = beneficiary_; _releaseTime = releaseTime_; } /** * @return the token being held. */ function token() public view virtual returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() public view virtual returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public virtual { require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); uint256 amount = token().balanceOf(address(this)); require(amount > 0, "TokenTimelock: no tokens to release"); token().safeTransfer(beneficiary(), amount); } function getLockedAmount() public view virtual returns (uint256) { uint256 amount = token().balanceOf(address(this)); return amount; } }
Transfers tokens held by timelock to beneficiary./
function release() public virtual { require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); uint256 amount = token().balanceOf(address(this)); require(amount > 0, "TokenTimelock: no tokens to release"); token().safeTransfer(beneficiary(), amount); }
66,672
./partial_match/1/0xb85849a0B793e2Acaeb619dDf844e574B169F1D2/sources/contracts/BaseRewardPool.sol
Processes queued rewards in isolation, providing the period has finished. This allows a cheaper way to trigger rewards on low value pools./
function processIdleRewards() external { if (block.timestamp >= periodFinish && queuedRewards > 0) { notifyRewardAmount(queuedRewards); queuedRewards = 0; } }
3,905,009
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./interfaces/IMySpace.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IBlackListAgent.sol"; import "./libraries/SafeMath256.sol"; contract SpaceLogic is IERC20, IMySpace { using SafeMath256 for uint; struct AdInfo { address coinType; uint64 endTime; uint numAudience; uint coinsPerAudience; } address private owner; address private chirp; address private voteCoin; uint private warmupTime; uint64 public nextThreadId; uint64 public nextVoteId; uint64 public nextAdId; address private blackListAgent; mapping(address => uint64/*timestamp*/) immatureFollowerTable; mapping(address => bool) followerTable; //accountName in blackList cannot be follower, if it already be, remove it mapping(bytes32 => bool) blackList; //voteConfig: 8bit, lsb represents if one vote only one ticket, silence vote coinAmount param; mapping(uint64/*vote id*/ => uint /*64bit end time | 8bit voteConfig | 8bit optionCount*/) voteTable; //no need hash mapping(bytes32 => uint) voteTallyTable; mapping(uint64/*ad id*/ => AdInfo) adTable; mapping(uint64 => mapping(address => bool)) adCoinReceivers; bool public coinLock; string private _name; uint8 private _decimal; string public _symbol; uint256 public _totalSupply; mapping(address => uint) public _balanceOf; mapping(address => mapping(address => uint)) public _allowance; function initCoin(string coinName, string coinSymbol, uint8 coinDecimal, uint initSupply) external { require(coinLock != true && msg.sender == owner); coinLock = true; _name = coinName; _symbol = coinSymbol; _decimal = coinDecimal; _totalSupply = initSupply; _balanceOf[owner] = initSupply; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function decimals() external view override returns (uint8) { return _decimal; } function _mint(address to, uint value) internal { _totalSupply = _totalSupply.add(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { _balanceOf[from] = _balanceOf[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address _owner, address spender, uint value) private { _allowance[_owner][spender] = value; emit Approval(_owner, spender, value); } function _transfer(address from, address to, uint value) private { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (_allowance[from][msg.sender] != uint256(2 ^ 256 - 1)) { _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function mint(uint amount) external { require(msg.sender == owner); _totalSupply += amount; _balanceOf[owner] += amount; } function totalSupply() external view override returns (uint) { return _totalSupply; } function balanceOf(address _owner) external view override returns (uint) { return _balanceOf[_owner]; } function allowance(address _owner, address spender) external view override returns (uint) { return _allowance[_owner][spender]; } //todo: only call by register, when change owner function switchToNewOwner(address _owner) external override { require(msg.sender == chirp); owner = _owner; } // Get the owner of this contract function getOwner() external view override returns (address) { return owner; } // Add the accounts in badIdList into blacklist. operator-only. function addToBlacklist(bytes32[] calldata badIdList) external override { require(msg.sender == owner); for (uint i = 0; i < badIdList.length; i++) { bytes32 acc = badIdList[i]; if (blackList[acc] != true) { blackList[acc] = true; address _owner = IRegistry(chirp).getOwnerByAccountName(acc); delete immatureFollowerTable[_owner]; delete followerTable[_owner]; } } } // Remove the accounts in goodIdList from blacklist. owner-only. function removeFromBlacklist(bytes32[] calldata goodIdList) external override { require(msg.sender == owner); for (uint i = 0; i < goodIdList.length; i++) { delete blackList[goodIdList[i]]; } } // Add another contract as blacklist agent. owner-only. function addBlacklistAgent(address agent) external override { require(msg.sender == owner); blackListAgent = agent; } // Stop taking another contract as blacklist agent. owner-only. //todo: only support one agent now; function removeBlacklistAgent() external override { require(msg.sender == owner); blackListAgent = address(0); } // Query wether an acc is in the black list function isInBlacklist(bytes32 accountName) public override returns (bool) { return blackList[accountName] || (blackListAgent != address(0) && IBlackListAgent(blackListAgent).isInBlacklist(accountName)); } // Create a new thread. Only the owner can call this function. Returns the new thread's id function createNewThread(bytes memory content, bytes32[] calldata notifyList) external override returns (uint64) { require(msg.sender == owner); uint64 threadId = nextThreadId; emit NewThread(threadId, content); uint length = notifyList.length; for (uint i = 0; i < (length + 1) / 2; i++) { if (2 * i + 1 == length) { emit Notify(threadId, notifyList[2 * i], bytes32("")); } else { emit Notify(threadId, notifyList[2 * i], notifyList[2 * i + 1]); } } nextThreadId++; return threadId; } // Add a comment under a thread. Only the owner and the followers can call this function function comment(uint64 threadId, bytes memory content, address rewardTo, uint rewardAmount, address rewardCoin) external override { require(msg.sender == owner || isFollower(msg.sender)); if (threadId < nextThreadId) { //todo: not check transfer result IERC20(rewardCoin).transferFrom(msg.sender, rewardTo, rewardAmount); emit NewComment(threadId, msg.sender, content, rewardTo, rewardAmount, rewardCoin); } } // Returns the Id of the next thread function getNextThreadId() external view override returns (uint64) { return nextThreadId; } // Follow this contract's owner. function follow() external override { require(followerTable[msg.sender] != true); bytes32 acc = IRegistry(chirp).getAccountNameByOwner(msg.sender); require(!isInBlacklist(acc)); immatureFollowerTable[msg.sender] = uint64(block.timestamp); } // Unfollow this contract's owner. function unfollow() external override { delete immatureFollowerTable[msg.sender]; delete followerTable[msg.sender]; } // Query all the followers, with paging support. // function getFollowers(uint start, uint count) external override returns (bytes32[] memory) { // return bytes32[](0); // } // Set the warmup time for new followers: how many hours after becoming a follower can she comment? owner-only //change numHours to numSeconds function setWarmupTime(uint numSeconds) external override { require(msg.sender == owner && numSeconds != 0); warmupTime = numSeconds; } // Query the warmup time for new followers function getWarmupTime() external view override returns (uint) { return warmupTime; } // Start a new vote. owner-only. Can delete an old vote to save gas. function startVote(string memory detail, uint8 optionCount, uint8 voteConfig, uint endTime, uint64 deleteOldId) external override returns (uint64) { require(msg.sender == owner && endTime > block.timestamp); uint64 voteId = nextVoteId; if (deleteOldId < voteId) { //todo: deleteOldId may not end uint info = voteTable[deleteOldId]; uint8 _optionCount = uint8(info); if (_optionCount != 0) { for (uint8 i = 0; i < _optionCount; i++) { delete voteTallyTable[keccak256(abi.encode(deleteOldId << 8 | i))]; } } delete voteTable[deleteOldId]; } voteTable[voteId] = endTime << 16 | voteConfig << 8 | optionCount; emit StartVote(voteId, detail, optionCount, endTime); nextVoteId++; return voteId; } // Vote for an option. followers-only. //todo: optionId should be [0,optionCount) function vote(uint64 voteId, uint8 optionId, uint coinAmount) external override { require(isFollower(msg.sender)); uint info = voteTable[voteId]; uint64 endTime = uint64(info >> 16); uint8 config = uint8(info >> 8); uint8 optionCount = uint8(info); if (endTime != 0 && block.timestamp < endTime && optionId < optionCount) { //not like a on chain gov vote, pay coins is not refund to user, voteCoin may be address zero always; if ((config & 0x01 == 0x01) || voteCoin == address(0)) { voteTallyTable[keccak256(abi.encode(voteId << 8 | optionId))] += 1; emit Vote(msg.sender, voteId, optionId, 1); } else if (IERC20(voteCoin).transferFrom(msg.sender, owner, coinAmount)) { voteTallyTable[keccak256(abi.encode(voteId << 8 | optionId))] += coinAmount; emit Vote(msg.sender, voteId, optionId, coinAmount); } } } // Return the amounts of voted coins for each option. function getVoteResult(uint64 voteId) external view override returns (uint[] memory) { uint voteInfo = voteTable[voteId]; //todo: not check if vote is end uint8 optionCount = uint8(voteInfo); require(optionCount != 0); uint[] memory tallyInfo = new uint[](optionCount); for (uint8 i = 0; i < optionCount; i++) { tallyInfo[i] = voteTallyTable[keccak256(abi.encode(voteId << 8 | i))]; } return tallyInfo; } // Returns the Id of the next vote function getNextVoteId() external view override returns (uint64) { return nextVoteId; } // Publish a new Ad. owner-only. Can delete an old Ad to save gas and reclaim coins at the same time. function publishAd(string memory detail, uint numAudience, uint coinsPerAudience, address coinType, uint endTime, uint64 deleteOldId) external override returns (uint64) { //coinType should impl IERC20 require(msg.sender == owner && endTime > block.timestamp && coinType != address(0)); uint64 id = nextAdId; AdInfo memory info; info.coinType = coinType; info.numAudience = numAudience; info.coinsPerAudience = coinsPerAudience; info.endTime = uint64(endTime); adTable[id] = info; //todo: coinType == 0 => native coin require(IERC20(coinType).transferFrom(msg.sender, address(this), numAudience * coinsPerAudience)); emit PublishAd(id, detail, numAudience, coinsPerAudience, coinType, endTime); if (deleteOldId < id) { AdInfo memory oldInfo = adTable[deleteOldId]; if (oldInfo.endTime != 0) { //not check if old ad if end or not delete adTable[deleteOldId]; //not check result IERC20(oldInfo.coinType).transfer(msg.sender, oldInfo.coinsPerAudience * oldInfo.numAudience); } } nextAdId++; return id; } // Click an Ad and express whether I am interested. followers-only function clickAd(uint id, bool interested) external override { require(isFollower(msg.sender)); AdInfo memory info = adTable[uint64(id)]; require(info.endTime > block.timestamp); if (!interested && info.numAudience > 0) { IERC20(info.coinType).transfer(msg.sender, info.coinsPerAudience); info.numAudience--; adTable[uint64(id)] = info; } emit ClickAd(uint64(id), msg.sender, interested); } // Delete an old Ad to save gas and reclaim coins function deleteAd(uint id) external override { require(msg.sender == owner); AdInfo memory oldInfo = adTable[uint64(id)]; if (oldInfo.endTime != 0) { //not check if old ad if end or not delete adTable[uint64(id)]; //not check result IERC20(oldInfo.coinType).transfer(msg.sender, oldInfo.coinsPerAudience * oldInfo.numAudience); } } // Returns the Id of the next Ad function getNextAdId() external view override returns (uint64) { return nextAdId; } function setVoteCoin(address coin) external { voteCoin = coin; } function getVoteCoin() external view returns (address) { return voteCoin; } function isFollower(address user) internal returns (bool) { bool _isFollower; if (followerTable[user] == true) { _isFollower = true; } else if (immatureFollowerTable[user] + warmupTime > block.timestamp) { _isFollower = true; followerTable[user] = true; delete immatureFollowerTable[user]; } return _isFollower; } } contract Space { address private owner; address private chirp; constructor(address _owner, address _chirp){ owner = _owner; chirp = _chirp; } receive() external payable {} fallback() payable external { address space = IRegistry(chirp).getSpaceLogic(); assembly { let ptr := mload(0x40) let size := calldatasize() calldatacopy(ptr, 0, size) let result := delegatecall(gas(), space, ptr, size, 0, 0) size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } }
Add the accounts in badIdList into blacklist. operator-only.
function addToBlacklist(bytes32[] calldata badIdList) external override { require(msg.sender == owner); for (uint i = 0; i < badIdList.length; i++) { bytes32 acc = badIdList[i]; if (blackList[acc] != true) { blackList[acc] = true; address _owner = IRegistry(chirp).getOwnerByAccountName(acc); delete immatureFollowerTable[_owner]; delete followerTable[_owner]; } } }
7,277,797
./full_match/1/0x73cD8626b3cD47B009E68380720CFE6679A3Ec3D/sources/contracts/LockupPlans/VotingTokenLockupPlans.sol
this function lets an owner delegate all of their lockup plans for a single token to a single delegatee this function will iterate through all of the owned lockup plans of the msg.sender, and if the token address matches the lockup plan token address, it will delegate that plan token is the ERC20Votes token address of the tokens in the lockup plans delegatee is the address of the delegate that the beneficiary is delegating their tokens to
function delegateAll(address token, address delegatee) external nonReentrant { uint256 balance = balanceOf(msg.sender); for (uint256 i; i < balance; i++) { uint256 planId = tokenOfOwnerByIndex(msg.sender, i); if (plans[planId].token == token) _delegate(planId, delegatee); } }
4,922,660
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./RandomNumberGenerator.sol"; import "./UnlimitedToken.sol"; /** @title Unlimited Evolution */ contract UnlimitedEvolution is ERC1155, ERC1155Holder, Ownable { /** * @dev Allows you to receive ERC1155 tokens and therefore make external calls to mint. * @param interfaceId Id of the interface. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155Receiver) returns(bool) { return super.supportsInterface(interfaceId); } uint8 constant BASIC_SWORD = 1; uint8 constant BASIC_SHIELD = 2; uint8 constant EXCALIBUR = 3; uint8 constant AEGIS = 4; uint8 constant POTION = 5; uint8 nextStuffId = 6; uint16 nextBruteId = 256; uint24 nextSpiritualId = 40256; uint24 nextElementaryId = 80256; uint24 limitMint = 4000; uint24[] countMints = new uint8[](3); uint256 mintFee = 0.001 ether; // Only for tests, to avoid chainlink bool public testMode; UnlimitedToken public unlimitedToken; RandomNumberGenerator public randomNumberGenerator; enum type_character { BRUTE, SPIRITUAL, ELEMENTARY } enum gender_character { MASCULINE, FEMININE, OTHER } enum type_stuff { WEAPON, SHIELD, POTION } struct Character { uint8 weapon; uint8 shield; uint16 rewards; uint16 level; uint24 id; uint24 xp; uint24 hp; uint24 stamina; uint24 attack1; uint24 attack2; uint24 defence1; uint24 defence2; uint256 lastRest; type_character typeCharacter; gender_character genderCharacter; } struct Stuff { uint8 id; uint8 bonusAttack1; uint8 bonusAttack2; uint8 bonusDefence1; uint8 bonusDefence2; uint256 mintPrice; type_stuff typeStuff; } // Mapping from token ID to token details mapping(uint24 => Character) private _characterDetails; // Mapping from token ID to token details mapping(uint8 => Stuff) private _stuffDetails; // Mapping from account to his number of NFTs mapping(address => uint8) private _balanceOfCharacters; /** * @dev Constructor of the contract ERC1155, mint stuff and add it to the mapping. * @param _unlimitedTokenAddress Address of the contract UnlimitedToken. * @param _randomNumberGenerator Address of the contract RandomNumberGenerator. */ constructor(UnlimitedToken _unlimitedTokenAddress, RandomNumberGenerator _randomNumberGenerator) ERC1155("ipfs://QmbbLcmiZ3Qtu3kc2LQoR4d87tWPpbkiRuERpV2fN4HDTm/{id}.json") { unlimitedToken = _unlimitedTokenAddress; randomNumberGenerator = _randomNumberGenerator; _mint(address(this), BASIC_SWORD, 10**5, bytes(abi.encodePacked("Unlimited Evolution Stuff #", Strings.toString(BASIC_SWORD)))); _stuffDetails[BASIC_SWORD] = Stuff(BASIC_SWORD, 2, 2, 0, 0, 0.001 ether, type_stuff.WEAPON); _mint(address(this), BASIC_SHIELD, 10**5, bytes(abi.encodePacked("Unlimited Evolution Stuff #", Strings.toString(BASIC_SHIELD)))); _stuffDetails[BASIC_SHIELD] = Stuff(BASIC_SHIELD, 0, 0, 2, 2, 0.001 ether, type_stuff.SHIELD); _mint(address(this), EXCALIBUR, 1, bytes(abi.encodePacked("Unlimited Evolution Stuff #", Strings.toString(EXCALIBUR)))); _stuffDetails[EXCALIBUR] = Stuff(EXCALIBUR, 10, 10, 10, 10, 0.1 ether, type_stuff.WEAPON); _mint(address(this), AEGIS, 1, bytes(abi.encodePacked("Unlimited Evolution Stuff #", Strings.toString(AEGIS)))); _stuffDetails[AEGIS] = Stuff(AEGIS, 10, 10, 10, 10, 0.1 ether, type_stuff.SHIELD); _mint(address(this), POTION, 10**6, bytes(abi.encodePacked("Unlimited Evolution Potion #", Strings.toString(POTION)))); _stuffDetails[POTION] = Stuff(POTION, 0, 0, 0, 0, 0.001 ether, type_stuff.POTION); } /** * @dev Emitted when the character with "id" is created. */ event CharacterCreated(uint24 id); /** * @dev Emitted when the character with "id" is rested, he recovers health points and stamina. */ event Rested(uint24 tokenId); /** * @dev Emitted when the character with "myTokenId" removes "substrateLifeToRival" points of hp to "rivalTokenId" and the character with "rivalTokenId" removes "substrateLifeToMe" points of hp to "myTokenId". */ event Fighted(uint24 myTokenId, uint24 rivalTokenId, uint256 substrateLifeToRival, uint256 substrateLifeToMe); /** * @dev Emitted when the character with "tokenId" has gained enough experience points to increase one level. */ event LevelUp(uint24 tokenId, uint16 level); /** * @dev Emitted when the owner changes the ether fee for minting, with the amount "mintFee". */ event MintFeeUpdated(uint256 mintFee); /** * @dev Emitted when the owner changes the mintable NFT limit with the amount "limitMint". */ event LimitUpdated(uint24 limitMint); /** * @dev Emitted when the msg.sender buy a stuff ". */ event StuffBought(uint8 stuffId); /** * @dev Emitted when the msg.sender burn a potion. */ event StuffEquiped(uint24 tokenId, uint8 stuffId); /** * @dev Emitted when the msg.sender burn a potion. */ event PotionUsed(uint24 tokenId); /** * @dev Change the token's image URI * @param _tokenId Id of the token. */ function uri(uint _tokenId) override public pure returns(string memory) { return string(abi.encodePacked( "ipfs://QmbbLcmiZ3Qtu3kc2LQoR4d87tWPpbkiRuERpV2fN4HDTm/", Strings.toString(_tokenId), ".json" )); } /** * @dev Return the name of the contract */ function name() public pure returns(string memory) { return "Unlimited Evolution"; } /** * @dev The function changes the ERC20 token address * @param _tokenAddress New token address. */ function setTokenAddress(address _tokenAddress) external onlyOwner { unlimitedToken = UnlimitedToken(_tokenAddress); } /** * @dev The function changes the Chainlink Random Number Generator address * @param _randomAddress New token address. */ function setLinkAddress(address _randomAddress) external onlyOwner { randomNumberGenerator = RandomNumberGenerator(_randomAddress); } /** * @dev The function changes the ether fee for minting. * @param _mintFee New amount of fee. * Emits a "MintFeeUpdated" event. */ function updateMintFee(uint256 _mintFee) external onlyOwner { mintFee = _mintFee; emit MintFeeUpdated(mintFee); } /** * @dev The function changes the mintable NFT limit. * @param _limitMint New limit of mintable NFT. * Emits a "LimitUpdated" event. */ function updateLimitMint(uint24 _limitMint) external onlyOwner { limitMint = _limitMint; emit LimitUpdated(limitMint); } /** * @dev Owner withdraws the entire amount of MATIC. */ function withdrawMatic() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * @dev Tip to simulate the function ownerOf of ERC721, check if msg.sender is owner of the token. * @param _tokenId Id of the token. * @return Boolean, true of false. */ function _ownerOf(uint256 _tokenId) private view returns(bool) { return balanceOf(msg.sender, _tokenId) != 0; } // /** // * @dev Allows you to create a new Stuff. // * Warning: Prefer to use createStuff() rather than manageStuff(), more secure with nextStuffId. // * @param amount Amount of NFT mintable. // * @param bonusAttack1 Bonus value attack1. // * @param bonusAttack2 Bonus value attack2. // * @param bonusDefence1 Bonus value defence1. // * @param bonusDefence2 Bonus value defence2. // * @param typeStuff Type of the stuff. // */ // function createStuff(uint256 amount, uint8 bonusAttack1, uint8 bonusAttack2, uint8 bonusDefence1, uint8 bonusDefence2, uint256 price, type_stuff typeStuff) external onlyOwner { // require(nextStuffId < 256, "The NFT Stuff limit is reached"); // _mint(address(this), nextStuffId, amount, ""); // _stuffDetails[nextStuffId] = Stuff(nextStuffId, bonusAttack1, bonusAttack2, bonusDefence1, bonusDefence2, price, typeStuff); // nextStuffId++; // } /** * @dev Allows you to create a new Stuff/Consumable and to modify the quantity, statistics and type of an existing NFT Stuff. * Warning: Be extremely careful with this function ! If you want to create a new NFT Stuff, prefer to use createStuff() ! * @param stuffId Id of the stuff. * @param amount Amount of NFT mintable. * @param bonusAttack1 Bonus value attack1. * @param bonusAttack2 Bonus value attack2. * @param bonusDefence1 Bonus value defence1. * @param bonusDefence2 Bonus value defence2. * @param typeStuff Type of the stuff. */ function manageStuff(uint8 stuffId, uint256 amount, uint8 bonusAttack1, uint8 bonusAttack2, uint8 bonusDefence1, uint8 bonusDefence2, uint256 price, type_stuff typeStuff) external onlyOwner { _mint(address(this), stuffId, amount, ""); if (stuffId != 5) { _stuffDetails[stuffId] = Stuff(stuffId, bonusAttack1, bonusAttack2, bonusDefence1, bonusDefence2, price, typeStuff); } } /** * @dev The function assigns a number between 3 and 5 randomly to the attack characteristics using "randomNumber". * @param randomNumber Random number from chainlink. * @return Array of number (attributes). */ function _attributesMintDistribution(uint256 randomNumber) private pure returns(uint8[] memory) { uint8[] memory _attributes = new uint8[](4); for(uint8 i=0; i<4; i++) { _attributes[i] = 3 + uint8((randomNumber % (10+i)) % 3); } return _attributes; } /** * @dev The Function ask to Chainlink a random number before to mint an NFT. * @param _typeCharacter Type of character between BRUTE, SPIRITUAL, ELEMENTARY. * @param _genderCharacter Gender of character between MASCULINE, FEMININE, OTHER. */ function askCreateCharacter(type_character _typeCharacter, gender_character _genderCharacter) external payable { require(msg.value == mintFee, "Wrong amount of fees"); require(_balanceOfCharacters[msg.sender] < 5, "You can't have more than 5 NFT"); require(countMints[uint8(_typeCharacter)] <= limitMint, "You cannot mint more character with this class"); if (!testMode) { // Only for tests, to avoid chainlink randomNumberGenerator.getRandomNumberMint(_typeCharacter, _genderCharacter, msg.sender); } else { this.createCharacter(_typeCharacter, _genderCharacter, uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, msg.sender))) % 10**16, msg.sender); } } /** * @dev The Function mint an NFT. * @param _typeCharacter Type of character between BRUTE, SPIRITUAL, ELEMENTARY. * @param _genderCharacter Gender of character between MASCULINE, FEMININE, OTHER. * @param randomNumber Random number from chainlink. * @param _address Address of the requestor (necessary for chainlink). * Emits a "CharacterCreated" event. */ function createCharacter(type_character _typeCharacter, gender_character _genderCharacter, uint256 randomNumber, address _address) external { require(msg.sender == address(randomNumberGenerator) || msg.sender == address(this), "Not allowed to use this function"); uint8[] memory _attributes = _attributesMintDistribution(randomNumber); uint24 nextCharacterId; if(_typeCharacter == type_character.BRUTE) { nextCharacterId = nextBruteId; } else if (_typeCharacter == type_character.SPIRITUAL) { nextCharacterId = nextSpiritualId; } else { nextCharacterId = nextElementaryId; } _characterDetails[nextCharacterId] = Character(0, 0, 0, 1, nextCharacterId, 1, 100, 100, _attributes[0], _attributes[1], _attributes[2], _attributes[3], 0, _typeCharacter, _genderCharacter); _balanceOfCharacters[_address]++; countMints[uint8(_typeCharacter)]++; _mint(_address, nextCharacterId, 1, bytes(abi.encodePacked("Unlimited Evolution Character #", Strings.toString(nextCharacterId)))); emit CharacterCreated(nextCharacterId); if(_typeCharacter == type_character.BRUTE) { nextBruteId++; } else if (_typeCharacter == type_character.SPIRITUAL) { nextSpiritualId++; } else { nextElementaryId++; } } /** * @dev The function allows the NFT to recover 100 health points and 100 stamina points. * @param _tokenId Id of the token. * Emits a "Rested" event. */ function rest(uint24 _tokenId) external { require(_ownerOf(_tokenId), "You don't own this NFT"); require(_characterDetails[_tokenId].stamina < 100 || _characterDetails[_tokenId].hp < 100, "You're character is already rested"); _characterDetails[_tokenId].lastRest = block.timestamp; _characterDetails[_tokenId].stamina = 100; _characterDetails[_tokenId].hp = 100; emit Rested(_tokenId); } /** * @dev One experience point is added and if the experience number reaches % 10 == 0 then the NFT increases one level and gains 1 point of reward. * @param _tokenId Id of the token. * Emits a "LevelUp" event. */ function _xpLevelUp(uint24 _tokenId) private { _characterDetails[_tokenId].xp++; if (_characterDetails[_tokenId].xp % 10 == 0) { _characterDetails[_tokenId].level++; _characterDetails[_tokenId].rewards++; emit LevelUp(_tokenId, _characterDetails[_tokenId].level); } } // /** // * @dev The function allows the allocation of attribute points (rewards*10) to the different characteristics. // * @param _tokenId Id of the token. // * @param _attack1 Attack number 1 of the token. // * @param _attack2 Attack number 2 of the token. // * @param _defence1 Defence number 1 of the token. // * @param _defence2 Defence number 2 of the token. // */ // function attributesLevelUp(uint24 _tokenId, uint16 _attack1, uint16 _attack2, uint16 _defence1, uint16 _defence2) external { // require(_characterDetails[_tokenId].rewards * 10 == _attack1 + _attack2 + _defence1 + _defence2, "Wrong amount of points to attribute"); // _characterDetails[_tokenId].rewards = 0; // _characterDetails[_tokenId].attack1 += _attack1; // _characterDetails[_tokenId].attack2 += _attack2; // _characterDetails[_tokenId].defence1 += _defence1; // _characterDetails[_tokenId].defence2 += _defence2; // } /** * @dev Claim Rewards after LevelUp, gains potion and ULT. * @param _tokenId Id of the token. */ function claimRewards(uint24 _tokenId) external { require(_ownerOf(_tokenId), "You don't own this NFT"); require(_characterDetails[_tokenId].rewards > 0, "You don't have any reward"); uint16 rewards = _characterDetails[_tokenId].rewards; _characterDetails[_tokenId].rewards = 0; unlimitedToken.levelUpMint(msg.sender, rewards); this.safeTransferFrom(address(this), msg.sender, POTION, rewards, ""); } /** * @dev Fight algorithm: attack, defence and experience points are taken into account to determine a winner. * @param _id1 Id of the token number 1. * @param _id2 Id of the token number 2. * @return Number resulting from fight operations. */ function _substrateLife(uint24 _id1, uint24 _id2, uint256 randomNumber) private view returns(uint16) { uint16 op1 = uint16(((_characterDetails[_id1].attack1 + _characterDetails[_id1].attack2 + _characterDetails[_id1].xp) / 2) * (1 + randomNumber)); uint16 op2 = uint16((_characterDetails[_id2].defence1 + _characterDetails[_id2].defence2) / 2); if (op1 < op2) { return 0; } else { return op1 - op2; } } /** * @dev The Function manages the different scenarios during a fight. * @param _myTokenId Id of the token number 1. * @param _rivalTokenId Id of the token number 2. * @param _substrateLifeToRival Number of life points to remove from _rivalTokenId. * @param _substrateLifeToMe Number of life points to remove from _myTokenId. * Emits a "Fighted" event. */ function _subtrateLifeOperation(uint24 _myTokenId, uint24 _rivalTokenId, uint16 _substrateLifeToRival, uint16 _substrateLifeToMe) private { if(_substrateLifeToRival >= _characterDetails[_rivalTokenId].hp) { _characterDetails[_rivalTokenId].hp = 0; _xpLevelUp(_myTokenId); } else { _characterDetails[_rivalTokenId].hp = _characterDetails[_rivalTokenId].hp - uint24(_substrateLifeToRival); if(_substrateLifeToMe >= _characterDetails[_myTokenId].hp) { _characterDetails[_myTokenId].hp = 0; _xpLevelUp(_rivalTokenId); } else { _characterDetails[_myTokenId].hp = _characterDetails[_myTokenId].hp - uint24(_substrateLifeToMe); if (_substrateLifeToRival > _substrateLifeToMe) { _xpLevelUp(_myTokenId); } else if (_substrateLifeToMe > _substrateLifeToRival) { _xpLevelUp(_rivalTokenId); } else { _xpLevelUp(_myTokenId); _xpLevelUp(_rivalTokenId); } } } emit Fighted(_myTokenId, _rivalTokenId, _substrateLifeToRival, _substrateLifeToMe); } /** * @dev The Function ask to Chainlink a random number before to fight. * @param _myTokenId Id of the fighter number 1. * @param _rivalTokenId Id of the fighter number 2. */ function askFight(uint24 _myTokenId, uint24 _rivalTokenId) external { require(_ownerOf(_myTokenId), "You don't own this NFT"); require(_ownerOf(_myTokenId) != _ownerOf(_rivalTokenId), "Your NFTs cannot fight each other"); require(_characterDetails[_myTokenId].lastRest + 86400 < block.timestamp, "You're character is resting"); require(_characterDetails[_rivalTokenId].lastRest + 86400 < block.timestamp, "You're rival is resting"); require(_characterDetails[_myTokenId].stamina >= 10, "Not enough stamina"); require(_characterDetails[_myTokenId].level <= _characterDetails[_rivalTokenId].level, "Fight someone your own size!"); require(_characterDetails[_myTokenId].hp > 0 && _characterDetails[_rivalTokenId].hp > 0, "One of the NFTs is dead"); if (!testMode) { // Only for tests, to avoid chainlink randomNumberGenerator.getRandomNumberFight(_myTokenId, _rivalTokenId); } else { this.fight(_myTokenId, _rivalTokenId, uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, msg.sender))) % 3); } } /** * @dev The function allows you to use your NFT to fight with another NFT belonging to another user. * @param _myTokenId Id of the fighter number 1. * @param _rivalTokenId Id of the fighter number 2. * @param randomNumber Random number from chainlink. */ function fight(uint24 _myTokenId, uint24 _rivalTokenId, uint256 randomNumber) external { require(msg.sender == address(randomNumberGenerator) || msg.sender == address(this), "Not allowed to use this function"); uint16 _substrateLifeToRival = _substrateLife(_myTokenId, _rivalTokenId, randomNumber); uint16 _substrateLifeToMe = _substrateLife(_rivalTokenId, _myTokenId, 0); _characterDetails[_myTokenId].stamina = _characterDetails[_myTokenId].stamina - 10; _subtrateLifeOperation(_myTokenId, _rivalTokenId, _substrateLifeToRival, _substrateLifeToMe); } /** * @dev The function allows you to buy a stuff NFT * @param stuffId Id of the stuff. * Emits a "StuffBought" event. */ function buyStuff(uint8 stuffId) external payable { require(stuffId != 0, "Non-existent stuff"); require(balanceOf(address(this), stuffId) != 0, "Stuff no more available"); require(msg.value == _stuffDetails[stuffId].mintPrice, "Wrong amount of fees"); this.safeTransferFrom(address(this), msg.sender, stuffId, 1, ""); emit StuffBought(stuffId); } /** * @dev The function allows you to equip stuff to your NFT * @param tokenId Id of the token. * @param stuffId Id of the stuff to equip. * Emits a "StuffEquiped" event. */ function equipStuff(uint24 tokenId, uint8 stuffId) external { require(tokenId > 255, "Wrong kind of NFT (Stuff)"); require(_ownerOf(tokenId), "You don't own this NFT"); require(stuffId != POTION, "You can't equip a potion"); require(_ownerOf(stuffId), "You don't own this stuff"); type_stuff stuffType = _stuffDetails[stuffId].typeStuff; uint8 idStuffEquiped; if (stuffType == type_stuff.WEAPON) { idStuffEquiped = _characterDetails[tokenId].weapon; } else { idStuffEquiped = _characterDetails[tokenId].shield; } if (idStuffEquiped != 0) { _characterDetails[tokenId].attack1 -= _stuffDetails[idStuffEquiped].bonusAttack1; _characterDetails[tokenId].attack2 -= _stuffDetails[idStuffEquiped].bonusAttack2; _characterDetails[tokenId].defence1 -= _stuffDetails[idStuffEquiped].bonusDefence1; _characterDetails[tokenId].defence2 -= _stuffDetails[idStuffEquiped].bonusDefence2; } _characterDetails[tokenId].attack1 += _stuffDetails[stuffId].bonusAttack1; _characterDetails[tokenId].attack2 += _stuffDetails[stuffId].bonusAttack2; _characterDetails[tokenId].defence1 += _stuffDetails[stuffId].bonusDefence1; _characterDetails[tokenId].defence2 += _stuffDetails[stuffId].bonusDefence2; if (stuffType == type_stuff.WEAPON) { _characterDetails[tokenId].weapon = stuffId; } else { _characterDetails[tokenId].shield = stuffId; } emit StuffEquiped(tokenId, stuffId); } /** * @dev The function burn a POTION and restore the hp and stamina of your NFT * @param tokenId Id of the token. * Emits a "PotionUsed" event. */ function usePotion(uint24 tokenId) external { require(tokenId > 255, "Wrong kind of NFT (Stuff)"); require(_ownerOf(tokenId), "You don't own this NFT"); require(_ownerOf(POTION), "You don't own a potion"); require(_characterDetails[tokenId].stamina < 100 || _characterDetails[tokenId].hp < 100, "You're character is already rested"); _burn(msg.sender, POTION, 1); _characterDetails[tokenId].stamina = 100; _characterDetails[tokenId].hp = 100; emit PotionUsed(tokenId); } /** * @dev The function returns the characteristics of the NFT. * @param tokenId Id of the token. * @return Character Details of tokenId. */ function getTokenDetails(uint24 tokenId) external view returns(Character memory) { return _characterDetails[tokenId]; } /** * @dev The function returns the characteristics of the stuff. * @param stuffId Id of the stuff. * @return Stuff Details of stuffId. */ function getStuffDetails(uint8 stuffId) external view returns(Stuff memory) { return _stuffDetails[stuffId]; } /** * @dev The function returns an array with the characteristics of all my NFTs. * @return Array of characters. */ function getMyCharacters() external view returns(Character[] memory) { uint8 count; Character[] memory myCharacters = new Character[](_balanceOfCharacters[msg.sender]); for (uint16 i = 256; i < nextBruteId; i++) { if (_ownerOf(i)) { myCharacters[count] = _characterDetails[i]; count++; } } for (uint24 i = 40256; i < nextSpiritualId; i++) { if (_ownerOf(i)) { myCharacters[count] = _characterDetails[i]; count++; } } for (uint24 i = 80256; i < nextElementaryId; i++) { if (_ownerOf(i)) { myCharacters[count] = _characterDetails[i]; count++; } } return myCharacters; } /** * @dev The function returns an array with the characteristics of all the NFTs that don't belong to me. * @return Array of characters. */ function getOthersCharacters() external view returns(Character[] memory){ uint24 count; Character[] memory othersCharacters = new Character[]((nextBruteId - 256) + ((nextSpiritualId - 40256)) + (nextElementaryId - 80256) - _balanceOfCharacters[msg.sender]); for (uint16 i = 256; i < nextBruteId; i++) { if (!_ownerOf(i)) { othersCharacters[count] = _characterDetails[i]; count++; } } for (uint24 i = 40256; i < nextSpiritualId; i++) { if (!_ownerOf(i)) { othersCharacters[count] = _characterDetails[i]; count++; } } for (uint24 i = 80256; i < nextElementaryId; i++) { if (!_ownerOf(i)) { othersCharacters[count] = _characterDetails[i]; count++; } } return othersCharacters; } /** * @dev The function returns an array with the characteristics of all my Stuffs. * @return Array of stuffs. */ function getMyStuffs() external view returns(Stuff[] memory){ uint8 arrayCount; for (uint8 i; i < nextStuffId; i++) { if (i !=5 && _ownerOf(i)) { arrayCount++; } } Stuff[] memory myStuffs = new Stuff[](arrayCount); uint8 count; for (uint8 i; i < nextStuffId-1; i++) { if (i !=5 && _ownerOf(i)) { myStuffs[count] = _stuffDetails[i]; count++; } } return myStuffs; } // Only for tests, to avoid chainlink function testModeSwitch() external onlyOwner { testMode = !testMode; } }
Allows you to create a new Stuff/Consumable and to modify the quantity, statistics and type of an existing NFT Stuff. Warning: Be extremely careful with this function ! If you want to create a new NFT Stuff, prefer to use createStuff() ! stuffId Id of the stuff. amount Amount of NFT mintable. bonusAttack1 Bonus value attack1. bonusAttack2 Bonus value attack2. bonusDefence1 Bonus value defence1. bonusDefence2 Bonus value defence2. typeStuff Type of the stuff./
function manageStuff(uint8 stuffId, uint256 amount, uint8 bonusAttack1, uint8 bonusAttack2, uint8 bonusDefence1, uint8 bonusDefence2, uint256 price, type_stuff typeStuff) external onlyOwner { _mint(address(this), stuffId, amount, ""); if (stuffId != 5) { _stuffDetails[stuffId] = Stuff(stuffId, bonusAttack1, bonusAttack2, bonusDefence1, bonusDefence2, price, typeStuff); } }
2,557,995
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./NonFungibleRegistryEnumerableUpgradeable.sol"; import "./NonFungibleRegistryUpgradeable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol"; import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; /** * @title Hypernet Protocol Non Fungible Registry Factory * @author Todd Chapman * @dev Upgradable beacon factor contract for efficiently deploying new * Non Fungible Registries. * * See the Hypernet Protocol documentation for more information: * https://docs.hypernet.foundation/hypernet-protocol/governance * * See unit tests for example usage: * https://github.com/GoHypernet/hypernet-protocol/blob/dev/packages/contracts/test/upgradeable-factory-test.js */ contract UpgradeableRegistryFactory is AccessControlEnumerable { /// @dev address of our upgradeble registry with enumeration proxy beacon address public enumerableRegistryBeacon; /// @dev address of our upgradable registry proxy beacon address public registryBeacon; /// @dev address of registry that serves os the Hypernet User Profile registry address public hypernetProfileRegistry = address(0); /// @dev extra array storage fascilitates paginated UI address[] public enumerableRegistries; /// @dev extra array storage fascilitates paginated UI address[] public registries; /// @notice Use this mapping to find the true deployment address of a project's NFR via the project name /// @dev This mapping is updated everytime this is a new NFR created by the factory mapping (string => address) public nameToAddress; /// @notice Address indicating what ERC-20 token can be used with createRegistryByToken /// @dev This address variable is used in conjunction with burnFee and burnAddress for the registerByToken function. Setting to the zero address disables the feature. address public registrationToken; /// @notice The amount of registrationToken required to call createRegistryByToken /// @dev Be sure you check the number of decimals associated with the ERC-20 contract at the registrationToken address uint256 public registrationFee = 50e18; // assume 18 decimal places /// @notice This is the address where registrationToken is forwarded upon a call to createRegistryByToken /// @dev The amount of registrationToken sent to this address is equal to {registrationFee * burnFee / 10000} address public burnAddress; /** * @dev Emitted when `DEFAULT_ADMIN_ROLE` creates a new registry. */ event RegistryCreated(address registryAddress); /// @notice constructor called on contract deployment /// @param _admin address who can call the createRegistry function /// @param _names array of names for the registries created on deployment /// @param _symbols array of symbols for the registries created on deployment /// @param _registrars array of addresses to recieve the REGISTRAR_ROLE for the registries created on deployment /// @param _enumerableRegistry address of implementation of enumerable NFR /// @param _registry address of implementation of non-enumerable NFR /// @param _registrationToken address of ERC20 token used for enabling the creation of registries by burning token constructor(address _admin, string[] memory _names, string[] memory _symbols, address[] memory _registrars, address _enumerableRegistry, address _registry, address _registrationToken) { require(_names.length == _symbols.length, "RegistryFactory: Initializer arrays must be equal length."); require(_symbols.length == _registrars.length, "RegistryFactory: Initializer arrays must be equal length."); // set the administrator of the registry factory _setupRole(DEFAULT_ADMIN_ROLE, _admin); // deploy upgradable beacon instance of enumerable registry contract UpgradeableBeacon _enumerableRegistryBeacon = new UpgradeableBeacon(_enumerableRegistry); _enumerableRegistryBeacon.transferOwnership(_admin); enumerableRegistryBeacon = address(_enumerableRegistryBeacon); // deploy upgradable beacon instance of registry contract UpgradeableBeacon _registryBeacon = new UpgradeableBeacon(_registry); _registryBeacon.transferOwnership(_admin); registryBeacon = address(_registryBeacon); registrationToken = _registrationToken; burnAddress = _admin; // deploy initial enumerable registries for (uint256 i = 0; i < _names.length; ++i) { _createEnumerableRegistry(_names[i], _symbols[i], _registrars[i]); // use the first enumerable registry as the hypernet profile registry if (i == 0) { hypernetProfileRegistry = enumerableRegistries[0]; } } } /// @notice getNumberOfEnumerableRegistries getter function for reading the number of enumerable registries /// @dev useful for paginated UIs function getNumberOfEnumerableRegistries() public view returns (uint256 numReg) { numReg = enumerableRegistries.length; } /// @notice getNumberOfRegistries getter function for reading the number of registries /// @dev useful for paginated UIs function getNumberOfRegistries() public view returns (uint256 numReg) { numReg = registries.length; } /// @notice setProfileRegistryAddress change the address of the profile registry contract /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _hypernetProfileRegistry address of ERC721 token to use as profile contract function setProfileRegistryAddress(address _hypernetProfileRegistry) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); hypernetProfileRegistry = _hypernetProfileRegistry; } /// @notice setRegistrationToken setter function for configuring which ERC20 token is burned when adding new apps /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _registrationToken address of ERC20 token burned during registration function setRegistrationToken(address _registrationToken) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); registrationToken = _registrationToken; } /// @notice setRegistrationFee setter function for configuring how much token is burned when adding new apps /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _registrationFee burn fee amount function setRegistrationFee(uint256 _registrationFee) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); require(registrationFee >= 0, "RegistryFactory: Registration fee must be nonnegative."); registrationFee = _registrationFee; } /// @notice setBurnAddress setter function for configuring where tokens are sent when calling createRegistryByToken /// @dev can only be called by the DEFAULT_ADMIN_ROLE /// @param _burnAddress address where creation fee is to be sent function setBurnAddress(address _burnAddress) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to set parameters"); burnAddress = _burnAddress; } /// @notice createRegistry called by DEFAULT_ADMIN_ROLE to create registries without a fee /// @dev the registry inherents the same admin as the factory /// @param _name name of the registry that will be created /// @param _symbol symbol to associate with the registry /// @param _registrar address that will recieve the REGISTRAR_ROLE /// @param _enumerable boolean declaring if the registry should have the enumeration property function createRegistry(string calldata _name, string calldata _symbol, address _registrar, bool _enumerable) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "RegistryFactory: must have admin role to create a registry"); if (_enumerable) { _createEnumerableRegistry(_name, _symbol, _registrar); } else { _createRegistry(_name, _symbol, _registrar); } } /// @notice createRegistryByToken called by any user with sufficient registration token /// @dev the registry inherents the same admin as the factory /// @param _name name of the registry that will be created /// @param _symbol symbol to associate with the registry /// @param _registrar address that will recieve the REGISTRAR_ROLE function createRegistryByToken(string memory _name, string memory _symbol, address _registrar, bool _enumerable) external { require(_preRegistered(_msgSender()), "RegistryFactory: caller must have a Hypernet Profile."); require(registrationToken != address(0), "RegistryFactory: registration by token not enabled."); // user must call approve first require(IERC20Upgradeable(registrationToken).transferFrom(_msgSender(), burnAddress, registrationFee), "RegistryFactory: token transfer failed."); if (_enumerable) { _createEnumerableRegistry(_name, _symbol, _registrar); } else { _createRegistry(_name, _symbol, _registrar); } } function _createEnumerableRegistry(string memory _name, string memory _symbol, address _registrar) private { require(_registrar != address(0), "RegistryFactory: Registrar address must not be 0."); require(!_registryExists(_name), "RegistryFactory: Registry by that name exists."); // cloning the beacon implementation reduced gas by ~80% over naive approach BeaconProxy proxy = new BeaconProxy(enumerableRegistryBeacon, abi.encodeWithSelector(NonFungibleRegistryEnumerableUpgradeable.initialize.selector, _name, _symbol, hypernetProfileRegistry, _registrar, getRoleMember(DEFAULT_ADMIN_ROLE, 0))); enumerableRegistries.push(address(proxy)); nameToAddress[_name] = address(proxy); emit RegistryCreated(address(proxy)); } function _createRegistry(string memory _name, string memory _symbol, address _registrar) private { require(_registrar != address(0), "RegistryFactory: Registrar address must not be 0."); require(!_registryExists(_name), "RegistryFactory: Registry by that name exists."); // cloning the beacon implementation reduced gas by ~80% over naive approach BeaconProxy proxy = new BeaconProxy(registryBeacon, abi.encodeWithSelector(NonFungibleRegistryUpgradeable.initialize.selector, _name, _symbol, hypernetProfileRegistry, _registrar, getRoleMember(DEFAULT_ADMIN_ROLE, 0))); registries.push(address(proxy)); nameToAddress[_name] = address(proxy); emit RegistryCreated(address(proxy)); } function _registryExists(string memory _name) internal view virtual returns (bool) { // registry name must have non-zero length and must not exist already return !((bytes(_name).length > 0) && nameToAddress[_name] == address(0)); } function _preRegistered(address owner) internal view virtual returns (bool) { // check if there if a profile is required and if so // does the recipient have a non-zero balance. return ((hypernetProfileRegistry == address(0)) || (IERC721Upgradeable(hypernetProfileRegistry).balanceOf(owner) > 0)); } }
check if there if a profile is required and if so does the recipient have a non-zero balance.
function _preRegistered(address owner) internal view virtual returns (bool) { return ((hypernetProfileRegistry == address(0)) || (IERC721Upgradeable(hypernetProfileRegistry).balanceOf(owner) > 0)); }
14,055,384
//SPDX-License-Identifier: MIT //Deploy Wallet Factory instead of Wallet following the factory design pattern pragma solidity ^0.8.0; import "./MultiSigWallet.sol"; contract MultiSigWalletFactory { MultiSigWallet[] public wallets; address[] public walletCreators; function getWallets() public view returns (MultiSigWallet[] memory) { return wallets; } function getWalletCreators() public view returns (address[] memory) { return walletCreators; } // msg.sender is automatically added on frontend into _owners function createWallet( address[] calldata _owners, uint256 _percentConfirmationsRequired ) external returns (MultiSigWallet) { MultiSigWallet wallet = new MultiSigWallet( _owners, _percentConfirmationsRequired ); // index of wallets will match walletCreators wallets.push(wallet); walletCreators.push(_owners[0]); return wallet; } //Expose wallet interfaces function addOwner(MultiSigWallet wallet, address newOwner) external { wallet.addOwner(newOwner, msg.sender); } function removeOwner(MultiSigWallet wallet, address existingOwner) external { wallet.removeOwner(existingOwner, msg.sender); } function submitTransaction( MultiSigWallet wallet, address _from, address _to, uint256 _value, bytes calldata _data ) external { wallet.submitTransaction(_from, _to, _value, _data); } function confirmTransaction(MultiSigWallet wallet, uint256 _txIndex) external { wallet.confirmTransaction(_txIndex, msg.sender); } function executeTransaction(MultiSigWallet wallet, uint256 _txIndex) external { wallet.executeTransaction(_txIndex, msg.sender); } function revokeConfirmation(MultiSigWallet wallet, uint256 _txIndex) external { wallet.revokeConfirmation(_txIndex, msg.sender); } function setPercentConfirmationRequired( MultiSigWallet wallet, uint256 _percentConfirmationRequired ) external { wallet.setPercentConfirmationRequired( _percentConfirmationRequired, msg.sender ); } function isOwner(MultiSigWallet wallet, address _owner) public view returns (bool) { return wallet.isOwner(_owner); } function getOwners(MultiSigWallet wallet) public view returns (address[] memory) { return wallet.getOwners(); } function getTransactionCount(MultiSigWallet wallet) public view returns (uint256) { return wallet.getTransactionCount(); } function getTransaction(MultiSigWallet wallet, uint256 _txIndex) public view returns ( address from, address to, uint256 value, bytes memory data, bool executed, uint256 numConfirmations ) { return wallet.getTransaction(_txIndex); } function getPercentConfirmationRequired(MultiSigWallet wallet) public view returns (uint256) { return wallet.percentConfirmationRequired(); } }
msg.sender is automatically added on frontend into _owners index of wallets will match walletCreators
function createWallet( address[] calldata _owners, uint256 _percentConfirmationsRequired ) external returns (MultiSigWallet) { MultiSigWallet wallet = new MultiSigWallet( _owners, _percentConfirmationsRequired ); wallets.push(wallet); walletCreators.push(_owners[0]); return wallet; }
15,883,419
./full_match/1/0xf7E49a9D1dfeD8E533e3C6d2A5977e6d240e07f5/sources/contracts/QuestFactory.sol
Refund any excess payment
function processMintFee() private { uint change = msg.value - mintFee; if (change > 0) { msg.sender.safeTransferETH(change); emit ExtraMintFeeReturned(msg.sender, change); } }
4,968,753
/** *Submitted for verification at Etherscan.io on 2021-03-09 */ /** *Submitted for verification at Etherscan.io on 2021-02-22 */ // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // SPDX-License-Identifier: MIT pragma solidity 0.6.8; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer( address indexed _from, address indexed _to, uint256 _value ); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); } // File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @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 EnumMap for EnumMap.Map; * * // Declare a set state variable * EnumMap.Map private myMap; * } * ``` */ library EnumMap { // 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. // This means that we can only create new EnumMaps 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) internal 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) internal 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) internal 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) internal 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) internal view returns (bytes32, bytes32) { require(map.entries.length > index, "EnumMap: index out of bounds"); MapEntry storage entry = map.entries[index]; return (entry.key, entry.value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(Map storage map, bytes32 key) internal view returns (bytes32) { uint256 keyIndex = map.indexes[key]; require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key) return map.entries[keyIndex - 1].value; // All indexes are 1-based } } // File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @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 EnumSet for EnumSet.Set; * * // Declare a set state variable * EnumSet.Set private mySet; * } * ``` */ library EnumSet { // 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. // 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) internal 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) internal 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) internal view returns (bool) { return set.indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(Set storage set) internal 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) internal view returns (bytes32) { require(set.values.length > index, "EnumSet: index out of bounds"); return set.values[index]; } } // File @openzeppelin/contracts/GSN/[email protected] pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.6.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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @animoca/ethereum-contracts-core_library/contracts/payment/[email protected] pragma solidity 0.6.8; /** @title PayoutWallet @dev adds support for a payout wallet Note: . */ contract PayoutWallet is Ownable { event PayoutWalletSet(address payoutWallet_); address payable public payoutWallet; constructor(address payoutWallet_) internal { setPayoutWallet(payoutWallet_); } function setPayoutWallet(address payoutWallet_) public onlyOwner { require(payoutWallet_ != address(0), "The payout wallet must not be the zero address"); require(payoutWallet_ != address(this), "The payout wallet must not be the contract itself"); require(payoutWallet_ != payoutWallet, "The payout wallet must be different"); payoutWallet = payable(payoutWallet_); emit PayoutWalletSet(payoutWallet); } } // File @animoca/ethereum-contracts-core_library/contracts/utils/[email protected] pragma solidity 0.6.8; /** * Contract module which allows derived contracts to implement a mechanism for * activating, or 'starting', a contract. * * This module is used through inheritance. It will make available the modifiers * `whenNotStarted` and `whenStarted`, which can be applied to the functions of * your contract. Those functions will only be 'startable' once the modifiers * are put in place. */ contract Startable is Context { event Started(address account); uint256 private _startedAt; /** * Modifier to make a function callable only when the contract has not started. */ modifier whenNotStarted() { require(_startedAt == 0, "Startable: started"); _; } /** * Modifier to make a function callable only when the contract has started. */ modifier whenStarted() { require(_startedAt != 0, "Startable: not started"); _; } /** * Constructor. */ constructor () internal {} /** * Returns the timestamp when the contract entered the started state. * @return The timestamp when the contract entered the started state. */ function startedAt() public view returns (uint256) { return _startedAt; } /** * Triggers the started state. * @dev Emits the Started event when the function is successfully called. */ function _start() internal virtual whenNotStarted { _startedAt = now; emit Started(_msgSender()); } } // File @openzeppelin/contracts/utils/Pau[email protected] pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected] pragma solidity 0.6.8; /** * @title ISale * * An interface for a contract which allows merchants to display products and customers to purchase them. * * Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an * explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment * tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means * this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment. * * The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used * to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver * contract address can be set for a SKU at its creation: if the value is different from the zero address, * the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU. * * This interface is designed to be consistent while managing a variety of implementation scenarios. It is * also intended to be developer-friendly: all vital information is consistently deductible from the events * (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented). */ interface ISale { /** * Event emitted to notify about the magic values necessary for interfacing with this contract. * @param names An array of names for the magic values used by the contract. * @param values An array of values for the magic values used by the contract. */ event MagicValues(bytes32[] names, bytes32[] values); /** * Event emitted to notify about the creation of a SKU. * @param sku The identifier of the created SKU. * @param totalSupply The initial total supply for sale. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after * each purchase. If this is the zero address, the call is not enabled. */ event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver); /** * Event emitted to notify about a change in the pricing of a SKU. * @dev `tokens` and `prices` arrays MUST have the same length. * @param sku The identifier of the updated SKU. * @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled. * @param prices An array of updated prices for each of the payment tokens. * Zero price values are used for payment tokens being disabled. */ event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices); /** * Event emitted to notify about a purchase. * @param purchaser The initiater and buyer of the purchase. * @param recipient The recipient of the purchase. * @param token The token used as the currency for the payment. * @param sku The identifier of the purchased SKU. * @param quantity The purchased quantity. * @param userData Optional extra user input data. * @param totalPrice The amount of `token` paid. * @param extData Implementation-specific extra purchase data, such as * details about discounts applied, conversion rates, purchase receipts, etc. */ event Purchase( address indexed purchaser, address recipient, address indexed token, bytes32 indexed sku, uint256 quantity, bytes userData, uint256 totalPrice, bytes extData ); /** * Returns the magic value used to represent the ETH payment token. * @dev MUST NOT be the zero address. * @return the magic value used to represent the ETH payment token. */ // solhint-disable-next-line func-name-mixedcase function TOKEN_ETH() external pure returns (address); /** * Returns the magic value used to represent an infinite, never-decreasing SKU's supply. * @dev MUST NOT be zero. * @return the magic value used to represent an infinite, never-decreasing SKU's supply. */ // solhint-disable-next-line func-name-mixedcase function SUPPLY_UNLIMITED() external pure returns (uint256); /** * Performs a purchase. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the address zero. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @dev Emits the Purchase event. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. */ function purchaseFor( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external payable; /** * Estimates the computed final total amount to pay for a purchase, including any potential discount. * @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time). * @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @param recipient The recipient of the purchase used to calculate the total price amount. * @param token The payment token used to calculate the total price amount. * @param sku The identifier of the SKU used to calculate the total price amount. * @param quantity The quantity used to calculate the total price amount. * @param userData Optional extra user input data. * @return totalPrice The computed total price to pay. * @return pricingData Implementation-specific extra pricing data, such as details about discounts applied. * If not empty, the implementer MUST document how to interepret the values. */ function estimatePurchase( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external view returns (uint256 totalPrice, bytes32[] memory pricingData); /** * Returns the information relative to a SKU. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of payment tokens is bounded, so that this function does not run out of gas. * @dev Reverts if `sku` does not exist. * @param sku The SKU identifier. * @return totalSupply The initial total supply for sale. * @return remainingSupply The remaining supply for sale. * @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. * @return tokens The list of supported payment tokens. * @return prices The list of associated prices for each of the `tokens`. */ function getSkuInfo(bytes32 sku) external view returns ( uint256 totalSupply, uint256 remainingSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver, address[] memory tokens, uint256[] memory prices ); /** * Returns the list of created SKU identifiers. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of SKUs is bounded, so that this function does not run out of gas. * @return skus the list of created SKU identifiers. */ function getSkus() external view returns (bytes32[] memory skus); } // File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected] pragma solidity 0.6.8; /** * @title IPurchaseNotificationsReceiver * Interface for any contract that wants to support purchase notifications from a Sale contract. */ interface IPurchaseNotificationsReceiver { /** * Handles the receipt of a purchase notification. * @dev This function MUST return the function selector, otherwise the caller will revert the transaction. * The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector` * @dev This function MAY throw. * @param purchaser The purchaser of the purchase. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. * @param totalPrice The total price paid. * @param pricingData Implementation-specific extra pricing data, such as details about discounts applied. * @param paymentData Implementation-specific extra payment data, such as conversion rates. * @param deliveryData Implementation-specific extra delivery data, such as purchase receipts. * @return `bytes4(keccak256( * "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))` */ function onPurchaseNotificationReceived( address purchaser, address recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData, uint256 totalPrice, bytes32[] calldata pricingData, bytes32[] calldata paymentData, bytes32[] calldata deliveryData ) external returns (bytes4); } // File @animoca/ethereum-contracts-sale_base/contracts/sale/abstract/[email protected] pragma solidity 0.6.8; /** * @title PurchaseLifeCycles * An abstract contract which define the life cycles for a purchase implementer. */ abstract contract PurchaseLifeCycles { /** * Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions. */ struct PurchaseData { address payable purchaser; address payable recipient; address token; bytes32 sku; uint256 quantity; bytes userData; uint256 totalPrice; bytes32[] pricingData; bytes32[] paymentData; bytes32[] deliveryData; } /* Internal Life Cycle Functions */ /** * `estimatePurchase` lifecycle. * @param purchase The purchase conditions. */ function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) { _validation(purchase); _pricing(purchase); totalPrice = purchase.totalPrice; pricingData = purchase.pricingData; } /** * `purchaseFor` lifecycle. * @param purchase The purchase conditions. */ function _purchaseFor(PurchaseData memory purchase) internal virtual { _validation(purchase); _pricing(purchase); _payment(purchase); _delivery(purchase); _notification(purchase); } /* Internal Life Cycle Step Functions */ /** * Lifecycle step which validates the purchase pre-conditions. * @dev Responsibilities: * - Ensure that the purchase pre-conditions are met and revert if not. * @param purchase The purchase conditions. */ function _validation(PurchaseData memory purchase) internal view virtual; /** * Lifecycle step which computes the purchase price. * @dev Responsibilities: * - Computes the pricing formula, including any discount logic and price conversion; * - Set the value of `purchase.totalPrice`; * - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it. * @param purchase The purchase conditions. */ function _pricing(PurchaseData memory purchase) internal view virtual; /** * Lifecycle step which manages the transfer of funds from the purchaser. * @dev Responsibilities: * - Ensure the payment reaches destination in the expected output token; * - Handle any token swap logic; * - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it. * @param purchase The purchase conditions. */ function _payment(PurchaseData memory purchase) internal virtual; /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update; * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual; /** * Lifecycle step which notifies of the purchase. * @dev Responsibilities: * - Manage after-purchase event(s) emission. * - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable. * @param purchase The purchase conditions. */ function _notification(PurchaseData memory purchase) internal virtual; } // File @animoca/ethereum-contracts-sale_base/contracts/sale/abstract/[email protected] pragma solidity 0.6.8; /** * @title Sale * An abstract base sale contract with a minimal implementation of ISale and administration functions. * A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions * are provided, but the inheriting contract must implement `_pricing` and `_payment`. */ abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable { using Address for address; using SafeMath for uint256; using EnumSet for EnumSet.Set; using EnumMap for EnumMap.Map; struct SkuInfo { uint256 totalSupply; uint256 remainingSupply; uint256 maxQuantityPerPurchase; address notificationsReceiver; EnumMap.Map prices; } address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max; EnumSet.Set internal _skus; mapping(bytes32 => SkuInfo) internal _skuInfos; uint256 internal immutable _skusCapacity; uint256 internal immutable _tokensPerSkuCapacity; /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param payoutWallet_ the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address payoutWallet_, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) internal PayoutWallet(payoutWallet_) { _skusCapacity = skusCapacity; _tokensPerSkuCapacity = tokensPerSkuCapacity; bytes32[] memory names = new bytes32[](2); bytes32[] memory values = new bytes32[](2); (names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH))); (names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED))); emit MagicValues(names, values); _pause(); } /* Public Admin Functions */ /** * Actvates, or 'starts', the contract. * @dev Emits the `Started` event. * @dev Emits the `Unpaused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has already been started. * @dev Reverts if the contract is not paused. */ function start() public virtual onlyOwner { _start(); _unpause(); } /** * Pauses the contract. * @dev Emits the `Paused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has not been started yet. * @dev Reverts if the contract is already paused. */ function pause() public virtual onlyOwner whenStarted { _pause(); } /** * Resumes the contract. * @dev Emits the `Unpaused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has not been started yet. * @dev Reverts if the contract is not paused. */ function unpause() public virtual onlyOwner whenStarted { _unpause(); } /** * Sets the token prices for the specified product SKU. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if `tokens` and `prices` have different lengths. * @dev Reverts if `sku` does not exist. * @dev Reverts if one of the `tokens` is the zero address. * @dev Reverts if the update results in too many tokens for the SKU. * @dev Emits the `SkuPricingUpdate` event. * @param sku The identifier of the SKU. * @param tokens The list of payment tokens to update. * If empty, disable all the existing payment tokens. * @param prices The list of prices to apply for each payment token. * Zero price values are used to disable a payment token. */ function updateSkuPricing( bytes32 sku, address[] memory tokens, uint256[] memory prices ) public virtual onlyOwner { uint256 length = tokens.length; // solhint-disable-next-line reason-string require(length == prices.length, "Sale: tokens/prices lengths mismatch"); SkuInfo storage skuInfo = _skuInfos[sku]; require(skuInfo.totalSupply != 0, "Sale: non-existent sku"); EnumMap.Map storage tokenPrices = skuInfo.prices; if (length == 0) { uint256 currentLength = tokenPrices.length(); for (uint256 i = 0; i < currentLength; ++i) { // TODO add a clear function in EnumMap and EnumSet and use it (bytes32 token, ) = tokenPrices.at(0); tokenPrices.remove(token); } } else { _setTokenPrices(tokenPrices, tokens, prices); } emit SkuPricingUpdate(sku, tokens, prices); } /* ISale Public Functions */ /** * Performs a purchase. * @dev Reverts if the sale has not started. * @dev Reverts if the sale is paused. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @dev Emits the Purchase event. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. */ function purchaseFor( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external payable virtual override whenStarted whenNotPaused { PurchaseData memory purchase; purchase.purchaser = _msgSender(); purchase.recipient = recipient; purchase.token = token; purchase.sku = sku; purchase.quantity = quantity; purchase.userData = userData; _purchaseFor(purchase); } /** * Estimates the computed final total amount to pay for a purchase, including any potential discount. * @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time). * @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values. * @dev Reverts if the sale has not started. * @dev Reverts if the sale is paused. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @param recipient The recipient of the purchase used to calculate the total price amount. * @param token The payment token used to calculate the total price amount. * @param sku The identifier of the SKU used to calculate the total price amount. * @param quantity The quantity used to calculate the total price amount. * @param userData Optional extra user input data. * @return totalPrice The computed total price. * @return pricingData Implementation-specific extra pricing data, such as details about discounts applied. * If not empty, the implementer MUST document how to interepret the values. */ function estimatePurchase( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external view virtual override whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory pricingData) { PurchaseData memory purchase; purchase.purchaser = _msgSender(); purchase.recipient = recipient; purchase.token = token; purchase.sku = sku; purchase.quantity = quantity; purchase.userData = userData; return _estimatePurchase(purchase); } /** * Returns the information relative to a SKU. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of payment tokens is bounded, so that this function does not run out of gas. * @dev Reverts if `sku` does not exist. * @param sku The SKU identifier. * @return totalSupply The initial total supply for sale. * @return remainingSupply The remaining supply for sale. * @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. * @return tokens The list of supported payment tokens. * @return prices The list of associated prices for each of the `tokens`. */ function getSkuInfo(bytes32 sku) external view override returns ( uint256 totalSupply, uint256 remainingSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver, address[] memory tokens, uint256[] memory prices ) { SkuInfo storage skuInfo = _skuInfos[sku]; uint256 length = skuInfo.prices.length(); totalSupply = skuInfo.totalSupply; require(totalSupply != 0, "Sale: non-existent sku"); remainingSupply = skuInfo.remainingSupply; maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase; notificationsReceiver = skuInfo.notificationsReceiver; tokens = new address[](length); prices = new uint256[](length); for (uint256 i = 0; i < length; ++i) { (bytes32 token, bytes32 price) = skuInfo.prices.at(i); tokens[i] = address(uint256(token)); prices[i] = uint256(price); } } /** * Returns the list of created SKU identifiers. * @return skus the list of created SKU identifiers. */ function getSkus() external view override returns (bytes32[] memory skus) { skus = _skus.values; } /* Internal Utility Functions */ /** * Creates an SKU. * @dev Reverts if `totalSupply` is zero. * @dev Reverts if `sku` already exists. * @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address. * @dev Reverts if the update results in too many SKUs. * @dev Emits the `SkuCreation` event. * @param sku the SKU identifier. * @param totalSupply the initial total supply. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver The purchase notifications receiver contract address. * If set to the zero address, the notification is not enabled. */ function _createSku( bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver ) internal virtual { require(totalSupply != 0, "Sale: zero supply"); require(_skus.length() < _skusCapacity, "Sale: too many skus"); require(_skus.add(sku), "Sale: sku already created"); if (notificationsReceiver != address(0)) { // solhint-disable-next-line reason-string require(notificationsReceiver.isContract(), "Sale: receiver is not a contract"); } SkuInfo storage skuInfo = _skuInfos[sku]; skuInfo.totalSupply = totalSupply; skuInfo.remainingSupply = totalSupply; skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase; skuInfo.notificationsReceiver = notificationsReceiver; emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver); } /** * Updates SKU token prices. * @dev Reverts if one of the `tokens` is the zero address. * @dev Reverts if the update results in too many tokens for the SKU. * @param tokenPrices Storage pointer to a mapping of SKU token prices to update. * @param tokens The list of payment tokens to update. * @param prices The list of prices to apply for each payment token. * Zero price values are used to disable a payment token. */ function _setTokenPrices( EnumMap.Map storage tokenPrices, address[] memory tokens, uint256[] memory prices ) internal virtual { for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; require(token != address(0), "Sale: zero address token"); uint256 price = prices[i]; if (price == 0) { tokenPrices.remove(bytes32(uint256(token))); } else { tokenPrices.set(bytes32(uint256(token)), bytes32(price)); } } require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens"); } /* Internal Life Cycle Step Functions */ /** * Lifecycle step which validates the purchase pre-conditions. * @dev Responsibilities: * - Ensure that the purchase pre-conditions are met and revert if not. * @dev Reverts if `purchase.recipient` is the zero address. * @dev Reverts if `purchase.token` is the zero address. * @dev Reverts if `purchase.quantity` is zero. * @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`. * @dev Reverts if `purchase.quantity` is greater than the available supply. * @dev Reverts if `purchase.sku` does not exist. * @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`. * @dev If this function is overriden, the implementer SHOULD super call this before. * @param purchase The purchase conditions. */ function _validation(PurchaseData memory purchase) internal view virtual override { require(purchase.recipient != address(0), "Sale: zero address recipient"); require(purchase.token != address(0), "Sale: zero address token"); require(purchase.quantity != 0, "Sale: zero quantity purchase"); SkuInfo storage skuInfo = _skuInfos[purchase.sku]; require(skuInfo.totalSupply != 0, "Sale: non-existent sku"); require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity"); if (skuInfo.totalSupply != SUPPLY_UNLIMITED) { require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply"); } bytes32 priceKey = bytes32(uint256(purchase.token)); require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token"); } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update; * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev If this function is overriden, the implementer SHOULD super call it. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { SkuInfo memory skuInfo = _skuInfos[purchase.sku]; if (skuInfo.totalSupply != SUPPLY_UNLIMITED) { _skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity); } } /** * Lifecycle step which notifies of the purchase. * @dev Responsibilities: * - Manage after-purchase event(s) emission. * - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable. * @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value. * @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData` * and `deliveryData`. If not empty, the implementer MUST document how to interpret these values. * @dev If this function is overriden, the implementer SHOULD super call it. * @param purchase The purchase conditions. */ function _notification(PurchaseData memory purchase) internal virtual override { emit Purchase( purchase.purchaser, purchase.recipient, purchase.token, purchase.sku, purchase.quantity, purchase.userData, purchase.totalPrice, abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData) ); address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver; if (notificationsReceiver != address(0)) { // solhint-disable-next-line reason-string require( IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived( purchase.purchaser, purchase.recipient, purchase.token, purchase.sku, purchase.quantity, purchase.userData, purchase.totalPrice, purchase.pricingData, purchase.paymentData, purchase.deliveryData ) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value "Sale: wrong receiver return value" ); } } } // File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected] pragma solidity 0.6.8; /** * @title FixedPricesSale * An Sale which implements a fixed prices strategy. * The final implementer is responsible for implementing any additional pricing and/or delivery logic. */ contract FixedPricesSale is Sale { /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param payoutWallet_ the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address payoutWallet_, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) internal Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {} /* Internal Life Cycle Functions */ /** * Lifecycle step which computes the purchase price. * @dev Responsibilities: * - Computes the pricing formula, including any discount logic and price conversion; * - Set the value of `purchase.totalPrice`; * - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it. * @dev Reverts if `purchase.sku` does not exist. * @dev Reverts if `purchase.token` is not supported by the SKU. * @dev Reverts in case of price overflow. * @param purchase The purchase conditions. */ function _pricing(PurchaseData memory purchase) internal view virtual override { SkuInfo storage skuInfo = _skuInfos[purchase.sku]; require(skuInfo.totalSupply != 0, "Sale: unsupported SKU"); EnumMap.Map storage prices = skuInfo.prices; uint256 unitPrice = _unitPrice(purchase, prices); purchase.totalPrice = unitPrice.mul(purchase.quantity); } /** * Lifecycle step which manages the transfer of funds from the purchaser. * @dev Responsibilities: * - Ensure the payment reaches destination in the expected output token; * - Handle any token swap logic; * - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it. * @dev Reverts in case of payment failure. * @param purchase The purchase conditions. */ function _payment(PurchaseData memory purchase) internal virtual override { if (purchase.token == TOKEN_ETH) { require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided"); payoutWallet.transfer(purchase.totalPrice); uint256 change = msg.value.sub(purchase.totalPrice); if (change != 0) { purchase.purchaser.transfer(change); } } else { require(IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice), "Sale: ERC20 payment failed"); } } /* Internal Utility Functions */ /** * Retrieves the unit price of a SKU for the specified payment token. * @dev Reverts if the specified payment token is unsupported. * @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved. * @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from. * @return unitPrice The unit price of a SKU for the specified payment token. */ function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) { unitPrice = uint256(prices.get(bytes32(uint256(purchase.token)))); require(unitPrice != 0, "Sale: unsupported payment token"); } } // File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected] pragma solidity 0.6.8; /** * @title FixedOrderInventorySale * A FixedPricesSale contract that handles the purchase of NFTs of an inventory contract to a * receipient. The provisioning of the NFTs occurs in a sequential order defined by a token list. * Only a single SKU is supported. */ contract FixedOrderInventorySale is FixedPricesSale { address public immutable inventory; uint256 public tokenIndex; uint256[] public tokenList; /** * Constructor. * @dev Reverts if `inventory_` is the zero address. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param inventory_ The inventory contract from which the NFT sale supply is attributed from. * @param payoutWallet The payout wallet. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address inventory_, address payoutWallet, uint256 tokensPerSkuCapacity ) public FixedPricesSale( payoutWallet, 1, // single SKU tokensPerSkuCapacity ) { // solhint-disable-next-line reason-string require(inventory_ != address(0), "FixedOrderInventorySale: zero address inventory"); inventory = inventory_; } /** * Adds additional tokens to the sale supply. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if `tokens` is empty. * @dev Reverts if any of `tokens` are zero. * @dev The list of tokens specified (in sequence) will be appended to the end of the ordered * sale supply list. * @param tokens The list of tokens to add. */ function addSupply(uint256[] memory tokens) public virtual onlyOwner { uint256 numTokens = tokens.length; // solhint-disable-next-line reason-string require(numTokens != 0, "FixedOrderInventorySale: empty tokens to add"); for (uint256 i = 0; i != numTokens; ++i) { uint256 token = tokens[i]; // solhint-disable-next-line reason-string require(token != 0, "FixedOrderInventorySale: adding zero token"); tokenList.push(token); } if (_skus.length() != 0) { bytes32 sku = _skus.at(0); SkuInfo storage skuInfo = _skuInfos[sku]; skuInfo.totalSupply += numTokens; skuInfo.remainingSupply += numTokens; } } /** * Sets the tokens of the ordered sale supply list. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if called when the contract is not paused. * @dev Reverts if the sale supply is empty. * @dev Reverts if the lengths of `indexes` and `tokens` do not match. * @dev Reverts if `indexes` is zero length. * @dev Reverts if any of `indexes` are less than `tokenIndex`. * @dev Reverts if any of `indexes` are out-of-bounds. * @dev Reverts it `tokens` is zero length. * @dev Reverts if any of `tokens` are zero. * @dev Does not allow resizing of the sale supply, only the re-ordering or replacment of * existing tokens. * @dev Because the elements of `indexes` and `tokens` are processed in sequence, duplicate * entries in either array are permitted, which allows for ordered operations to be performed * on the ordered sale supply list in the same transaction. * @param indexes The list of indexes in the ordered sale supply list whose element values * will be set. * @param tokens The new tokens to set in the ordered sale supply list at the corresponding * positions provided by `indexes`. */ function setSupply(uint256[] memory indexes, uint256[] memory tokens) public virtual onlyOwner whenPaused { uint256 tokenListLength = tokenList.length; // solhint-disable-next-line reason-string require(tokenListLength != 0, "FixedOrderInventorySale: empty token list"); uint256 numIndexes = indexes.length; // solhint-disable-next-line reason-string require(numIndexes != 0, "FixedOrderInventorySale: empty indexes"); uint256 numTokens = tokens.length; // solhint-disable-next-line reason-string require(numIndexes == numTokens, "FixedOrderInventorySale: array length mismatch"); uint256 tokenIndex_ = tokenIndex; for (uint256 i = 0; i != numIndexes; ++i) { uint256 index = indexes[i]; // solhint-disable-next-line reason-string require(index >= tokenIndex_, "FixedOrderInventorySale: invalid index"); // solhint-disable-next-line reason-string require(index < tokenListLength, "FixedOrderInventorySale: index out-of-bounds"); uint256 token = tokens[i]; // solhint-disable-next-line reason-string require(token != 0, "FixedOrderInventorySale: zero token"); tokenList[index] = token; } } /** * Retrieves the amount of total sale supply. * @return The amount of total sale supply. */ function getTotalSupply() public view virtual returns (uint256) { return tokenList.length; } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update. * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for * this purchase. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { super._delivery(purchase); purchase.deliveryData = new bytes32[](purchase.quantity); uint256 tokenCount = 0; uint256 tokenIndex_ = tokenIndex; while (tokenCount != purchase.quantity) { purchase.deliveryData[tokenCount] = bytes32(tokenList[tokenIndex_]); ++tokenCount; ++tokenIndex_; } tokenIndex = tokenIndex_; } } // File @animoca/f1dt-ethereum-contracts/contracts/sale/[email protected] pragma solidity 0.6.8; /** * @title FixedOrderTrackSale * A FixedOrderInventorySale contract implementation that handles the purchases of F1® DeltaTime * track NFTs by minting them from an inventory contract to the recipient. The provisioning of the * NFTs from the holder account occurs in a sequential order defined by a token list. Only a * single SKU is supported. */ contract FixedOrderTrackSale is FixedOrderInventorySale { /** * Constructor. * @dev Reverts if `inventory` is the zero address. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param inventory The inventory contract from which the NFT sale supply is attributed from. * @param payoutWallet The payout wallet. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address inventory, address payoutWallet, uint256 tokensPerSkuCapacity ) public FixedOrderInventorySale( inventory, payoutWallet, tokensPerSkuCapacity) {} /** * Creates an SKU. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if called when the contract is not paused. * @dev Reverts if the initial sale supply is empty. * @dev Reverts if `sku` already exists. * @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address. * @dev Reverts if the update results in too many SKUs. * @dev Emits the `SkuCreation` event. * @param sku the SKU identifier. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver The purchase notifications receiver contract address. * If set to the zero address, the notification is not enabled. */ function createSku( bytes32 sku, uint256 maxQuantityPerPurchase, address notificationsReceiver ) external onlyOwner whenPaused { _createSku(sku, tokenList.length, maxQuantityPerPurchase, notificationsReceiver); } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update. * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev Reverts if this contract does not have the minter role on the inventory contract. * @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for * this purchase. * @dev Mints the tokens allocated in `purchase.deliveryData` to the purchase recipient. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { super._delivery(purchase); address[] memory to = new address[](purchase.quantity); uint256[] memory ids = new uint256[](purchase.quantity); bytes32[] memory uris = new bytes32[](purchase.quantity); uint256[] memory values = new uint256[](purchase.quantity); IFixedOrderInventoryMintable mintableInventory = IFixedOrderInventoryMintable(inventory); for (uint256 index = 0; index != purchase.quantity; ++index) { to[index] = purchase.recipient; ids[index] = uint256(purchase.deliveryData[index]); uris[index] = ""; values[index] = 1; } mintableInventory.batchMint( to, ids, uris, values, false); } } /** * @dev Interface for the mint function of the NFT inventory contract. */ interface IFixedOrderInventoryMintable { /* * Mints a batch of new tokens. * @dev Reverts if some the given token IDs already exist. * @param to address[] List of addresses that will own the minted tokens. * @param ids uint256[] List of ids of the tokens to be minted. * @param uris bytes32[] Concatenated metadata URIs of nfts to be minted. * @param values uint256[] List of quantities of ft to be minted. */ function batchMint( address[] calldata to, uint256[] calldata ids, bytes32[] calldata uris, uint256[] calldata values, bool safe ) external; }
Retrieves the amount of total sale supply. return The amount of total sale supply./
function getTotalSupply() public view virtual returns (uint256) { return tokenList.length; }
7,883,516
./partial_match/1/0x45c7667632EA2562A68caa36da86509ae41547E3/sources/contracts/Votium.sol
transfer stored rewards to distributor (to rescue tokens sent directly to contract) does not change virtual balance
function rescueToDistributor(address _token) public onlyTeam { uint256 bal = IERC20(_token).balanceOf(address(this)) - virtualBalance[_token]; require(bal > 0, "!balance"); IERC20(_token).safeTransfer(distributor, bal); }
4,079,224
pragma solidity >=0.4.14 <0.6.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender)); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title 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); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * 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; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(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' require((value == 0) || (token.allowance(address(this), spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } /// @author QuarkChain Eng Team /// @title A simplified term deposit contract for ERC20 tokens contract TermDepositSimplified is WhitelistAdminRole { using SafeMath for uint256; using SafeERC20 for IERC20; event DoDeposit(address indexed depositor, uint256 amount); event Withdraw(address indexed depositor, uint256 amount); event Drain(address indexed admin); event Pause(address indexed admin, bool isPaused); event Goodbye(address indexed admin, uint256 amount); uint256 public constant MIN_DEPOSIT = 100 * 1e18; // => 100 QKC. // Pre-defined terms. bytes4 public constant TERM_2MO = "2mo"; bytes4 public constant TERM_4MO = "4mo"; bytes4 public constant TERM_6MO = "6mo"; struct TermDepositInfo { uint256 duration; uint256 totalReceived; mapping (address => Deposit[]) deposits; } struct Deposit { uint256 amount; uint256 depositAt; uint256 withdrawAt; } mapping (bytes4 => TermDepositInfo) private _termDeposits; IERC20 private _token; bool private _isPaused = false; bytes4[] public allTerms = [TERM_2MO, TERM_4MO, TERM_6MO]; /// Constructor for the term deposit contract. /// @param token ERC20 token addresses for term deposit constructor(IERC20 token) public { uint256 monthInSec = 2635200; _token = token; _termDeposits[TERM_2MO] = TermDepositInfo({ duration: 2 * monthInSec, totalReceived: 0 }); _termDeposits[TERM_4MO] = TermDepositInfo({ duration: 4 * monthInSec, totalReceived: 0 }); _termDeposits[TERM_6MO] = TermDepositInfo({ duration: 6 * monthInSec, totalReceived: 0 }); } /// Getter for token address. /// @return the token address function token() public view returns (IERC20) { return _token; } /// Return a term deposit's key properties. /// @param term the byte representation of terms /// @return a list of deposit overview info function getTermDepositInfo(bytes4 term) public view returns (uint256[2] memory) { TermDepositInfo memory info = _termDeposits[term]; require(info.duration > 0, "should be a valid term"); return [ info.duration, info.totalReceived ]; } /// Deposit users tokens into this contract. /// @param term the byte representation of terms /// @param amount token amount in wei function deposit(bytes4 term, uint256 amount) public { require(!_isPaused, "deposit not allowed when contract is paused"); require(amount >= MIN_DEPOSIT, "should have amount >= minimum"); TermDepositInfo storage info = _termDeposits[term]; require(info.duration > 0, "should be a valid term"); Deposit[] storage deposits = info.deposits[msg.sender]; deposits.push(Deposit({ amount: amount, depositAt: now, withdrawAt: 0 })); info.totalReceived = info.totalReceived.add(amount); emit DoDeposit(msg.sender, amount); _token.safeTransferFrom(msg.sender, address(this), amount); } /// Calculate amount of tokens a user has deposited. /// @param depositor the address of the depositor /// @param terms the list of byte representation of terms /// @param withdrawable boolean flag for whether to require withdrawable /// @return amount of tokens available for withdrawal function getDepositAmount( address depositor, bytes4[] memory terms, bool withdrawable ) public view returns (uint256[] memory) { uint256[] memory ret = new uint256[](terms.length); for (uint256 i = 0; i < terms.length; i++) { TermDepositInfo storage info = _termDeposits[terms[i]]; require(info.duration > 0, "should be a valid term"); Deposit[] memory deposits = info.deposits[depositor]; uint256 total = 0; for (uint256 j = 0; j < deposits.length; j++) { uint256 lockUntil = deposits[j].depositAt.add(info.duration); if (deposits[j].withdrawAt == 0) { if (!withdrawable || now >= lockUntil) { total = total.add(deposits[j].amount); } } } ret[i] = total; } return ret; } /// Get detailed deposit information of a user. /// @param depositor the address of the depositor /// @param terms the list of byte representation of terms /// @return 1 array for terms, 3 arrays of deposit amounts, deposit / withdrawal timestamps function getDepositDetails( address depositor, bytes4[] memory terms ) public view returns (bytes4[] memory, uint256[] memory, uint256[] memory, uint256[] memory) { Deposit[][] memory depositListByTerms = new Deposit[][](terms.length); // Collect count first because dynamic array in memory is not allowed. uint256 totalDepositCount = 0; for (uint256 i = 0; i < terms.length; i++) { bytes4 term = terms[i]; TermDepositInfo storage info = _termDeposits[term]; require(info.duration > 0, "should be a valid term"); Deposit[] memory deposits = info.deposits[depositor]; depositListByTerms[i] = deposits; totalDepositCount = totalDepositCount.add(deposits.length); } bytes4[] memory depositTerms = new bytes4[](totalDepositCount); uint256[] memory amounts = new uint256[](totalDepositCount); uint256[] memory depositTs = new uint256[](totalDepositCount); uint256[] memory withdrawTs = new uint256[](totalDepositCount); uint256 retIndex = 0; for (uint256 i = 0; i < depositListByTerms.length; i++) { Deposit[] memory deposits = depositListByTerms[i]; for (uint256 j = 0; j < deposits.length; j++) { depositTerms[retIndex] = terms[i]; Deposit memory d = deposits[j]; amounts[retIndex] = d.amount; depositTs[retIndex] = d.depositAt; withdrawTs[retIndex] = d.withdrawAt; retIndex += 1; } } assert(retIndex == totalDepositCount); return (depositTerms, amounts, depositTs, withdrawTs); } /// Withdraw a user's tokens plus interest to his/her own address. /// @param terms the list of byte representation of terms /// @return whether have withdrawn some tokens successfully function withdraw(bytes4[] memory terms) public returns (bool) { require(!_isPaused, "withdraw not allowed when contract is paused"); uint256 total = 0; for (uint256 i = 0; i < terms.length; i++) { bytes4 term = terms[i]; TermDepositInfo storage info = _termDeposits[term]; require(info.duration > 0, "should be a valid term"); Deposit[] storage deposits = info.deposits[msg.sender]; uint256 termTotal = 0; for (uint256 j = 0; j < deposits.length; j++) { uint256 lockUntil = deposits[j].depositAt.add(info.duration); if (deposits[j].withdrawAt == 0 && now >= lockUntil) { termTotal = termTotal.add(deposits[j].amount); deposits[j].withdrawAt = now; } } info.totalReceived = info.totalReceived.sub(termTotal); total = total.add(termTotal); } if (total == 0) { return false; } emit Withdraw(msg.sender, total); _token.safeTransfer(msg.sender, total); return true; } /// Return necessary amount of tokens to cover interests and referral bonuses. /// @param terms the list of byte representation of terms /// @return total deposit function calculateTotalPayout(bytes4[] memory terms) public view returns (uint256) { // [deposit, interest, bonus]. uint256 ret; for (uint256 i = 0; i < terms.length; i++) { TermDepositInfo memory info = _termDeposits[terms[i]]; require(info.duration > 0, "should be a valid term"); ret = ret.add(info.totalReceived); } return ret; } /// Leave enough tokens for payout, and drain the surplus. /// @dev only admins can call this function function drainSurplusTokens() external onlyWhitelistAdmin { emit Drain(msg.sender); uint256 neededAmount = calculateTotalPayout(allTerms); uint256 currentAmount = _token.balanceOf(address(this)); if (currentAmount > neededAmount) { uint256 surplus = currentAmount.sub(neededAmount); _token.safeTransfer(msg.sender, surplus); } } /// Pause deposit and withdraw /// @dev only admins can call this function function pause(bool isPaused) external onlyWhitelistAdmin { _isPaused = isPaused; emit Pause(msg.sender, _isPaused); } /// Drain remaining tokens and destroys the contract to save some space for the network. /// @dev only admins can call this function function goodbye() external onlyWhitelistAdmin { // Make sure is after deposit deadline, and no received tokens. for (uint256 i = 0; i < allTerms.length; i++) { bytes4 term = allTerms[i]; TermDepositInfo memory info = _termDeposits[term]; require(info.totalReceived < 1000 * 1e18, "should have small enough deposits"); } // Transfer remaining tokens. uint256 tokenAmount = _token.balanceOf(address(this)); emit Goodbye(msg.sender, tokenAmount); if (tokenAmount > 0) { _token.safeTransfer(msg.sender, tokenAmount); } // Say goodbye. selfdestruct(msg.sender); } }
Drain remaining tokens and destroys the contract to save some space for the network. only admins can call this function Make sure is after deposit deadline, and no received tokens.
function goodbye() external onlyWhitelistAdmin { for (uint256 i = 0; i < allTerms.length; i++) { bytes4 term = allTerms[i]; TermDepositInfo memory info = _termDeposits[term]; require(info.totalReceived < 1000 * 1e18, "should have small enough deposits"); } emit Goodbye(msg.sender, tokenAmount); if (tokenAmount > 0) { _token.safeTransfer(msg.sender, tokenAmount); } }
5,357,507
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT 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.7.6; interface ILiquidator { function liquidate( address recipient, address from, address to, uint256 amount, uint256 minOut ) external returns (uint256); function getSwapInfo(address from, address to) external view returns (address router, address[] memory path); function sushiswapRouter() external view returns (address); function uniswapRouter() external view returns (address); function weth() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IManager { function token() external view returns (address); function buybackFee() external view returns (uint256); function managementFee() external view returns (uint256); function liquidators(address from, address to) external view returns (address); function whitelisted(address _contract) external view returns (bool); function banks(uint256 i) external view returns (address); function totalBanks() external view returns (uint256); function strategies(address bank, uint256 i) external view returns (address); function totalStrategies(address bank) external view returns (uint256); function withdrawIndex(address bank) external view returns (uint256); function setWithdrawIndex(uint256 i) external; function rebalance(address bank) external; function finance(address bank) external; function financeAll(address bank) external; function buyback(address from) external; function accrueRevenue( address bank, address underlying, uint256 amount ) external; function exitAll(address bank) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IRegistry { function governance() external view returns (address); function manager() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ISubscriber { function registry() external view returns (address); function governance() external view returns (address); function manager() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IBankStorage} from "./IBankStorage.sol"; interface IBank is IBankStorage { function strategies(uint256 i) external view returns (address); function totalStrategies() external view returns (uint256); function underlyingBalance() external view returns (uint256); function strategyBalance(uint256 i) external view returns (uint256); function investedBalance() external view returns (uint256); function virtualBalance() external view returns (uint256); function virtualPrice() external view returns (uint256); function pause() external; function unpause() external; function invest(address strategy, uint256 amount) external; function investAll(address strategy) external; function exit(address strategy, uint256 amount) external; function exitAll(address strategy) external; function deposit(uint256 amount) external; function depositFor(uint256 amount, address recipient) external; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IBankStorage { function paused() external view returns (bool); function underlying() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IStrategyBase} from "./IStrategyBase.sol"; interface IStrategy is IStrategyBase { function investedBalance() external view returns (uint256); function invest() external; function withdraw(uint256 amount) external returns (uint256); function withdrawAll() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IStrategyStorage} from "./IStrategyStorage.sol"; interface IStrategyBase is IStrategyStorage { function underlyingBalance() external view returns (uint256); function derivativeBalance() external view returns (uint256); function rewardBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IStrategyStorage { function bank() external view returns (address); function underlying() external view returns (address); function derivative() external view returns (address); function reward() external view returns (address); // function investedBalance() external view returns (uint256); // function invest() external; // function withdraw(uint256 amount) external returns (uint256); // function withdrawAll() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IAaveV2StrategyStorage { function stakedToken() external view returns (address); function lendingPool() external view returns (address); function incentivesController() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library TransferHelper { using SafeERC20 for IERC20; // safely transfer tokens without underflowing function safeTokenTransfer( address recipient, address token, uint256 amount ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 balance = IERC20(token).balanceOf(address(this)); if (balance < amount) { IERC20(token).safeTransfer(recipient, balance); return balance; } else { IERC20(token).safeTransfer(recipient, amount); return amount; } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /// @title Oh! Finance Base Upgradeable /// @notice Contains internal functions to get/set primitive data types used by a proxy contract abstract contract OhUpgradeable { function getAddress(bytes32 slot) internal view returns (address _address) { // solhint-disable-next-line no-inline-assembly assembly { _address := sload(slot) } } function getBoolean(bytes32 slot) internal view returns (bool _bool) { uint256 bool_; // solhint-disable-next-line no-inline-assembly assembly { bool_ := sload(slot) } _bool = bool_ == 1; } function getBytes32(bytes32 slot) internal view returns (bytes32 _bytes32) { // solhint-disable-next-line no-inline-assembly assembly { _bytes32 := sload(slot) } } function getUInt256(bytes32 slot) internal view returns (uint256 _uint) { // solhint-disable-next-line no-inline-assembly assembly { _uint := sload(slot) } } function setAddress(bytes32 slot, address _address) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } function setBytes32(bytes32 slot, bytes32 _bytes32) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _bytes32) } } /// @dev Set a boolean storage variable in a given slot /// @dev Convert to a uint to take up an entire contract storage slot function setBoolean(bytes32 slot, bool _bool) internal { uint256 bool_ = _bool ? 1 : 0; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, bool_) } } function setUInt256(bytes32 slot, uint256 _uint) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _uint) } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ISubscriber} from "../interfaces/ISubscriber.sol"; import {IRegistry} from "../interfaces/IRegistry.sol"; import {OhUpgradeable} from "../proxy/OhUpgradeable.sol"; /// @title Oh! Finance Subscriber Upgradeable /// @notice Base Oh! Finance upgradeable contract used to control access throughout the protocol abstract contract OhSubscriberUpgradeable is Initializable, OhUpgradeable, ISubscriber { bytes32 private constant _REGISTRY_SLOT = 0x1b5717851286d5e98a28354be764b8c0a20eb2fbd059120090ee8bcfe1a9bf6c; /// @notice Only allow authorized addresses (governance or manager) to execute a function modifier onlyAuthorized { require(msg.sender == governance() || msg.sender == manager(), "Subscriber: Only Authorized"); _; } /// @notice Only allow the governance address to execute a function modifier onlyGovernance { require(msg.sender == governance(), "Subscriber: Only Governance"); _; } /// @notice Verify the registry storage slot is correct constructor() { assert(_REGISTRY_SLOT == bytes32(uint256(keccak256("eip1967.subscriber.registry")) - 1)); } /// @notice Initialize the Subscriber /// @param registry_ The Registry contract address /// @dev Always call this method in the initializer function for any derived classes function initializeSubscriber(address registry_) internal initializer { require(Address.isContract(registry_), "Subscriber: Invalid Registry"); _setRegistry(registry_); } /// @notice Set the Registry for the contract. Only callable by Governance. /// @param registry_ The new registry /// @dev Requires sender to be Governance of the new Registry to avoid bricking. /// @dev Ideally should not be used function setRegistry(address registry_) external onlyGovernance { _setRegistry(registry_); require(msg.sender == governance(), "Subscriber: Bad Governance"); } /// @notice Get the Governance address /// @return The current Governance address function governance() public view override returns (address) { return IRegistry(registry()).governance(); } /// @notice Get the Manager address /// @return The current Manager address function manager() public view override returns (address) { return IRegistry(registry()).manager(); } /// @notice Get the Registry address /// @return The current Registry address function registry() public view override returns (address) { return getAddress(_REGISTRY_SLOT); } function _setRegistry(address registry_) private { setAddress(_REGISTRY_SLOT, registry_); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IBank} from "../interfaces/bank/IBank.sol"; import {IStrategyBase} from "../interfaces/strategies/IStrategyBase.sol"; import {ILiquidator} from "../interfaces/ILiquidator.sol"; import {IManager} from "../interfaces/IManager.sol"; import {TransferHelper} from "../libraries/TransferHelper.sol"; import {OhSubscriberUpgradeable} from "../registry/OhSubscriberUpgradeable.sol"; import {OhStrategyStorage} from "./OhStrategyStorage.sol"; /// @title Oh! Finance Strategy /// @notice Base Upgradeable Strategy Contract to build strategies on contract OhStrategy is OhSubscriberUpgradeable, OhStrategyStorage, IStrategyBase { using SafeERC20 for IERC20; event Liquidate(address indexed router, address indexed token, uint256 amount); event Sweep(address indexed token, uint256 amount, address recipient); /// @notice Only the Bank can execute these functions modifier onlyBank() { require(msg.sender == bank(), "Strategy: Only Bank"); _; } /// @notice Initialize the base Strategy /// @param registry_ Address of the Registry /// @param bank_ Address of Bank /// @param underlying_ Underying token that is deposited /// @param derivative_ Derivative token received from protocol, or address(0) /// @param reward_ Reward token received from protocol, or address(0) function initializeStrategy( address registry_, address bank_, address underlying_, address derivative_, address reward_ ) internal initializer { initializeSubscriber(registry_); initializeStorage(bank_, underlying_, derivative_, reward_); } /// @dev Balance of underlying awaiting Strategy investment function underlyingBalance() public view override returns (uint256) { return IERC20(underlying()).balanceOf(address(this)); } /// @dev Balance of derivative tokens received from Strategy, if applicable /// @return The balance of derivative tokens function derivativeBalance() public view override returns (uint256) { if (derivative() == address(0)) { return 0; } return IERC20(derivative()).balanceOf(address(this)); } /// @dev Balance of reward tokens awaiting liquidation, if applicable function rewardBalance() public view override returns (uint256) { if (reward() == address(0)) { return 0; } return IERC20(reward()).balanceOf(address(this)); } /// @notice Governance function to sweep any stuck / airdrop tokens to a given recipient /// @param token The address of the token to sweep /// @param amount The amount of tokens to sweep /// @param recipient The address to send the sweeped tokens to function sweep( address token, uint256 amount, address recipient ) external onlyGovernance { // require(!_protected[token], "Strategy: Cannot sweep"); TransferHelper.safeTokenTransfer(recipient, token, amount); emit Sweep(token, amount, recipient); } /// @dev Liquidation function to swap rewards for underlying function liquidate( address from, address to, uint256 amount ) internal { // if (amount > minimumSell()) // find the liquidator to use address manager = manager(); address liquidator = IManager(manager).liquidators(from, to); // increase allowance and liquidate to the manager TransferHelper.safeTokenTransfer(liquidator, from, amount); uint256 received = ILiquidator(liquidator).liquidate(manager, from, to, amount, 1); // notify revenue and transfer proceeds back to strategy IManager(manager).accrueRevenue(bank(), to, received); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IStrategyStorage} from "../interfaces/strategies/IStrategyStorage.sol"; import {OhUpgradeable} from "../proxy/OhUpgradeable.sol"; contract OhStrategyStorage is Initializable, OhUpgradeable, IStrategyStorage { bytes32 internal constant _BANK_SLOT = 0xd2eff96e29993ca5431993c3a205e12e198965c0e1fdd87b4899b57f1e611c74; bytes32 internal constant _UNDERLYING_SLOT = 0x0fad97fe3ec7d6c1e9191a09a0c4ccb7a831b6605392e57d2fedb8501a4dc812; bytes32 internal constant _DERIVATIVE_SLOT = 0x4ff4c9b81c0bf267e01129f4817e03efc0163ee7133b87bd58118a96bbce43d3; bytes32 internal constant _REWARD_SLOT = 0xaeb865605058f37eedb4467ee2609ddec592b0c9a6f7f7cb0db3feabe544c71c; constructor() { assert(_BANK_SLOT == bytes32(uint256(keccak256("eip1967.strategy.bank")) - 1)); assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.strategy.underlying")) - 1)); assert(_DERIVATIVE_SLOT == bytes32(uint256(keccak256("eip1967.strategy.derivative")) - 1)); assert(_REWARD_SLOT == bytes32(uint256(keccak256("eip1967.strategy.reward")) - 1)); } function initializeStorage( address bank_, address underlying_, address derivative_, address reward_ ) internal initializer { _setBank(bank_); _setUnderlying(underlying_); _setDerivative(derivative_); _setReward(reward_); } /// @notice The Bank that the Strategy is associated with function bank() public view override returns (address) { return getAddress(_BANK_SLOT); } /// @notice The underlying token the Strategy invests in AaveV2 function underlying() public view override returns (address) { return getAddress(_UNDERLYING_SLOT); } /// @notice The derivative token received from AaveV2 (aToken) function derivative() public view override returns (address) { return getAddress(_DERIVATIVE_SLOT); } /// @notice The reward token received from AaveV2 (stkAave) function reward() public view override returns (address) { return getAddress(_REWARD_SLOT); } function _setBank(address _address) internal { setAddress(_BANK_SLOT, _address); } function _setUnderlying(address _address) internal { setAddress(_UNDERLYING_SLOT, _address); } function _setDerivative(address _address) internal { setAddress(_DERIVATIVE_SLOT, _address); } function _setReward(address _address) internal { setAddress(_REWARD_SLOT, _address); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ILendingPoolV2} from "./interfaces/ILendingPoolV2.sol"; import {ILendingPoolAddressesProviderV2} from "./interfaces/ILendingPoolAddressesProviderV2.sol"; import {IAaveIncentivesController} from "./interfaces/IAaveIncentivesController.sol"; import {IAaveProtocolDataProviderV2} from "./interfaces/IAaveProtocolDataProviderV2.sol"; import {IStakedToken} from "./interfaces/IStakedToken.sol"; /// @title Oh! Finance AaveV2 Helper /// @notice Helper functions to interact with the AaveV2 /// @dev https://docs.aave.com/portal/ abstract contract OhAaveV2Helper { using SafeERC20 for IERC20; /// @notice Get the AaveV2 aToken for a given underlying /// @param dataProvider The AaveV2 Data Provider /// @param underlying The underlying token to check /// @return The address of the associated aToken function aToken(address dataProvider, address underlying) internal view returns (address) { (address aTokenAddress, , ) = IAaveProtocolDataProviderV2(dataProvider).getReserveTokensAddresses(underlying); return aTokenAddress; } /// @notice Get the AaveV2 Lending Pool /// @param addressProvider The AaveV2 Address Provider /// @return The address of the AaveV2 Lending Pool function lendingPool(address addressProvider) internal view returns (address) { return ILendingPoolAddressesProviderV2(addressProvider).getLendingPool(); } /// @notice Get the cooldown timestamp start for this contract /// @param stakedToken The address of stkAAVE /// @return The timestamp the cooldown started on function stakersCooldown(address stakedToken) internal view returns (uint256) { uint256 stakerCooldown = IStakedToken(stakedToken).stakersCooldowns(address(this)); return stakerCooldown; } /// @notice Get the cooldown window in seconds for unstaking stkAAVE to AAVE before cooldown expires /// @dev 864000 - 10 days /// @param stakedToken The address of stkAAVE /// @return The cooldown seconds to wait before unstaking function cooldownWindow(address stakedToken) internal view returns (uint256) { uint256 window = IStakedToken(stakedToken).COOLDOWN_SECONDS(); return window; } /// @notice Get the unstake window in seconds for unstaking stkAAVE to AAVE after cooldown passes /// @dev 172800 - 2 days /// @param stakedToken The address of stkAAVE /// @return The unstake window seconds we have to unwrap stkAAVE to AAVE function unstakingWindow(address stakedToken) internal view returns (uint256) { uint256 window = IStakedToken(stakedToken).UNSTAKE_WINDOW(); return window; } /// @notice Initiate a claim cooldown to swap stkAAVE to AAVE /// @param stakedToken The address of stkAAVE function cooldown(address stakedToken) internal { IStakedToken(stakedToken).cooldown(); } /// @notice Redeem an amount of stkAAVE for AAVE /// @param stakedToken The address of stkAAVE /// @param amount The amount of stkAAVE to redeem function redeem(address stakedToken, uint256 amount) internal { if (amount == 0) { return; } IStakedToken(stakedToken).redeem(address(this), amount); } /// @notice Claim stkAAVE from the AaveV2 Incentive Controller /// @dev Claim all available rewards, return if none available /// @param incentivesController The AaveV2 Incentive Controller /// @param token The aToken to claim rewards for function claimRewards(address incentivesController, address token) internal { address[] memory tokens = new address[](1); tokens[0] = token; uint256 rewards = IAaveIncentivesController(incentivesController).getRewardsBalance(tokens, address(this)); if (rewards > 0) { IAaveIncentivesController(incentivesController).claimRewards(tokens, rewards, address(this)); } } /// @notice Lend underlying to Aave V2 Lending Pool, receive aTokens /// @param pool The AaveV2 Lending Pool /// @param underlying The underlying ERC20 to lend /// @param amount The amount of underlying to lend function lend( address pool, address underlying, uint256 amount ) internal { if (amount == 0) { return; } IERC20(underlying).safeIncreaseAllowance(pool, amount); ILendingPoolV2(pool).deposit( underlying, amount, address(this), 0 // referral code ); } /// @notice Reclaim underlying by sending aTokens to Aave V2 Lending Pool /// @param pool The AaveV2 Lending Pool /// @param token The aToken to redeem for underlying /// @param amount The amount of aTokens to send function reclaim( address pool, address token, uint256 amount ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 balance = IERC20(token).balanceOf(address(this)); IERC20(token).safeIncreaseAllowance(pool, amount); uint256 withdrawn = ILendingPoolV2(pool).withdraw(token, amount, address(this)); require(withdrawn == amount || withdrawn == balance, "AaveV2: Withdraw failed"); return withdrawn; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IStrategy} from "../../interfaces/strategies/IStrategy.sol"; import {TransferHelper} from "../../libraries/TransferHelper.sol"; import {OhStrategy} from "../OhStrategy.sol"; import {OhAaveV2Helper} from "./OhAaveV2Helper.sol"; import {OhAaveV2StrategyStorage} from "./OhAaveV2StrategyStorage.sol"; /// @title Oh! Finance Aave V2 Strategy /// @notice Standard strategy using Aave V2 Protocol /// @dev Underlying: USDC, USDT, etc. /// @dev Derivative: aToken, 1:1 ratio with underlying /// @dev https://docs.aave.com/developers/the-core-protocol/atokens contract OhAaveV2Strategy is IStrategy, OhAaveV2Helper, OhStrategy, OhAaveV2StrategyStorage { using SafeERC20 for IERC20; using SafeMath for uint256; /// @notice Initialize the AaveV2 Strategy Logic constructor() initializer { assert(registry() == address(0)); assert(bank() == address(0)); assert(underlying() == address(0)); assert(reward() == address(0)); } /// @notice Initialize the AaveV2 Strategy Proxy /// @param registry_ the registry contract /// @param bank_ the bank associated with the strategy /// @param underlying_ the underlying token that is deposited /// @param derivative_ the aToken address received from Aave /// @param reward_ the address of the reward token stkAAVE /// @param lendingPool_ the AaveV2 lending pool that we lend to /// @param incentivesController_ the AaveV2 rewards contract /// @dev The function should be called at time of deployment function initializeAaveV2Strategy( address registry_, address bank_, address underlying_, address derivative_, address reward_, address stakedToken_, address lendingPool_, address incentivesController_ ) public initializer { initializeStrategy(registry_, bank_, underlying_, derivative_, reward_); initializeAaveV2Storage(stakedToken_, lendingPool_, incentivesController_); } /// @notice Balance of underlying invested in AaveV2 /// @dev aTokens are 1:1 with underlying, they are continuously distributed to users function investedBalance() public view override returns (uint256) { return derivativeBalance(); } /// @notice Balance of stkAAVE await liquidation /// @dev Rewards are first received in stkAAVe, then must undergo 10 day cooldown /// @dev Before batch claiming. function stakedBalance() public view returns (uint256) { return IERC20(stakedToken()).balanceOf(address(this)); } /// @notice Invest in the AaveV2 Strategy /// @dev Compound by claiming stkAAVE, then unwrapping + liquidating if cooldown permits /// @dev Deposit all underlying to receive aTokens function invest() external override onlyBank { _compound(); _deposit(); } /// @notice function withdraw(uint256 amount) external override onlyBank returns (uint256) { uint256 withdrawn = _withdraw(msg.sender, amount); return withdrawn; } /// @notice function withdrawAll() external override onlyBank { uint256 amount = derivativeBalance(); _withdraw(msg.sender, amount); } /// @dev Compound stkAAVE rewards on a alternating cooldown schedule function _compound() internal { uint256 currentCooldown = rewardCooldown(); // if the current cooldown has passed if (block.timestamp > currentCooldown) { // save state variables uint256 balance = stakedBalance(); address staked = stakedToken(); uint256 expiration = currentCooldown.add(unstakingWindow(staked)); // if we have stkAAVE and the unstaking window hasn't passed if (balance > 0 && block.timestamp < expiration) { // redeem all available AAVE redeem(staked, balance); // validate we received AAVE uint256 amount = rewardBalance(); if (amount > 0) { // liquidate for underlying liquidate(reward(), underlying(), amount); } } // claim new batch of available stkAAVE rewards claimRewards(incentivesController(), derivative()); balance = stakedBalance(); if (balance > 0) { // initiate a new cooldown cooldown(staked); // validate the cooldown was set uint256 newCooldown = stakersCooldown(staked); require(newCooldown == block.timestamp, "AaveV2: Cooldown failed"); // find reward cooldown, new timestamp when rewards are claimable uint256 newRewardCooldown = newCooldown.add(cooldownWindow(staked)); _setRewardCooldown(newRewardCooldown); } } } function _deposit() internal { uint256 amount = underlyingBalance(); if (amount > 0) { lend(lendingPool(), underlying(), amount); } } // withdraw tokens from protocol after converting aTokens to underlying function _withdraw(address recipient, uint256 amount) internal returns (uint256) { if (amount == 0) { return 0; } uint256 reclaimed = reclaim(lendingPool(), underlying(), amount); uint256 withdrawn = TransferHelper.safeTokenTransfer(recipient, underlying(), reclaimed); return withdrawn; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IAaveV2StrategyStorage} from "../../interfaces/strategies/aave/IAaveV2StrategyStorage.sol"; import {OhUpgradeable} from "../../proxy/OhUpgradeable.sol"; contract OhAaveV2StrategyStorage is Initializable, OhUpgradeable, IAaveV2StrategyStorage { bytes32 internal constant _STAKED_TOKEN_SLOT = 0x6ffcc641b9dd32ae63496168decfef38477654371686576c048aacac7664aa89; bytes32 internal constant _LENDING_POOL_SLOT = 0x32da969ce0980814ec712773a44ab0fbc7a926f6c25ab5c3ab143cbaf257713b; bytes32 internal constant _INCENTIVES_CONTROLLER_SLOT = 0x8354a0ba382ef5f265c75cfb638fc27db941b9db0fd5dc17719a651d5d4cda15; bytes32 internal constant _REWARD_COOLDOWN_SLOT = 0x29ba1167c1adca0c8d6bf06d5964666a1db7a70ebfda62e977c0e3331d7b3923; constructor() { assert(_STAKED_TOKEN_SLOT == bytes32(uint256(keccak256("eip1967.aaveV2Strategy.stakedToken")) - 1)); assert(_LENDING_POOL_SLOT == bytes32(uint256(keccak256("eip1967.aaveV2Strategy.lendingPool")) - 1)); assert(_INCENTIVES_CONTROLLER_SLOT == bytes32(uint256(keccak256("eip1967.aaveV2Strategy.incentivesController")) - 1)); assert(_REWARD_COOLDOWN_SLOT == bytes32(uint256(keccak256("eip1967.aaveV2Strategy.rewardCooldown")) - 1)); } function initializeAaveV2Storage( address stakedToken_, address lendingPool_, address incentiveController_ ) internal initializer { _setStakedToken(stakedToken_); _setLendingPool(lendingPool_); _setIncentiveController(incentiveController_); _setRewardCooldown(block.timestamp + 864000); // initialize with 10 day reward lag } function stakedToken() public view override returns (address) { return getAddress(_STAKED_TOKEN_SLOT); } function lendingPool() public view override returns (address) { return getAddress(_LENDING_POOL_SLOT); } function incentivesController() public view override returns (address) { return getAddress(_INCENTIVES_CONTROLLER_SLOT); } function rewardCooldown() public view returns (uint256) { return getUInt256(_REWARD_COOLDOWN_SLOT); } function _setStakedToken(address stakedToken_) internal { setAddress(_STAKED_TOKEN_SLOT, stakedToken_); } function _setLendingPool(address lendingPool_) internal { setAddress(_LENDING_POOL_SLOT, lendingPool_); } function _setIncentiveController(address incentiveController_) internal { setAddress(_INCENTIVES_CONTROLLER_SLOT, incentiveController_); } function _setRewardCooldown(uint256 rewardCooldown_) internal { setUInt256(_REWARD_COOLDOWN_SLOT, rewardCooldown_); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {DistributionTypes} from "../libraries/DistributionTypes.sol"; interface IAaveDistributionManager { event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndUpdated(uint256 newDistributionEnd); /** * @dev Sets the end date for the distribution * @param distributionEnd The end date timestamp **/ function setDistributionEnd(uint256 distributionEnd) external; /** * @dev Gets the end date for the distribution * @return The end of the distribution **/ function getDistributionEnd() external view returns (uint256); /** * @dev for backwards compatibility with the previous DistributionManager used * @return The end of the distribution **/ function DISTRIBUTION_END() external view returns (uint256); /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {IAaveDistributionManager} from "./IAaveDistributionManager.sol"; interface IAaveIncentivesController { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed(address indexed user, address indexed to, address indexed claimer, uint256 amount); event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IAaveProtocolDataProviderV2 { function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ILendingPoolAddressesProviderV2 { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProviderV2} from "./ILendingPoolAddressesProviderV2.sol"; import {DataTypes} from "../libraries/DataTypes.sol"; interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit(address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay(address indexed reserve, address indexed user, address indexed repayer, uint256 amount); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IStakedToken { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function stakersCooldowns(address staker) external view returns (uint256); function COOLDOWN_SECONDS() external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint104 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } }
Get the unstake window in seconds for unstaking stkAAVE to AAVE after cooldown passes 172800 - 2 days stakedToken The address of stkAAVE return The unstake window seconds we have to unwrap stkAAVE to AAVE
function unstakingWindow(address stakedToken) internal view returns (uint256) { uint256 window = IStakedToken(stakedToken).UNSTAKE_WINDOW(); return window; }
6,990,362
// File: contracts/token/interfaces/IERC20Token.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} 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); } // File: contracts/IBancorNetwork.sol pragma solidity 0.4.26; /* Bancor Network interface */ contract IBancorNetwork { function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256); function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256); // deprecated, backward compatibility function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256); // deprecated, backward compatibility function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public payable returns (uint256); // deprecated, backward compatibility function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for ) public returns (uint256); } // File: contracts/IConversionPathFinder.sol pragma solidity 0.4.26; /* Conversion Path Finder interface */ contract IConversionPathFinder { function findPath(address _sourceToken, address _targetToken) public view returns (address[] memory); } // File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.4.26; /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.4.26; /* Converter Anchor interface */ contract IConverterAnchor is IOwned, ITokenHolder { } // File: contracts/utility/interfaces/IWhitelist.sol pragma solidity 0.4.26; /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } // File: contracts/converter/interfaces/IConverter.sol pragma solidity 0.4.26; /* Converter interface */ contract IConverter is IOwned { function converterType() public pure returns (uint16); function anchor() public view returns (IConverterAnchor) {this;} function isActive() public view returns (bool); function rateAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view returns (uint256, uint256); function convert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address _beneficiary) public payable returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {this;} function conversionFee() public view returns (uint32) {this;} function maxConversionFee() public view returns (uint32) {this;} function reserveBalance(IERC20Token _reserveToken) public view returns (uint256); function() external payable; function transferAnchorOwnership(address _newOwner) public; function acceptAnchorOwnership() public; function setConversionFee(uint32 _conversionFee) public; function setConversionWhitelist(IWhitelist _whitelist) public; function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; function withdrawETH(address _to) public; function addReserve(IERC20Token _token, uint32 _ratio) public; // deprecated, backward compatibility function token() public view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) public; function acceptTokenOwnership() public; function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool); function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256); function connectorTokens(uint256 _index) public view returns (IERC20Token); function connectorTokenCount() public view returns (uint16); } // File: contracts/converter/interfaces/IBancorFormula.sol pragma solidity 0.4.26; /* Bancor Formula interface */ contract IBancorFormula { function purchaseRate(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public view returns (uint256); function saleRate(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public view returns (uint256); function crossReserveRate(uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount) public view returns (uint256); function fundCost(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public view returns (uint256); function liquidateRate(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public view returns (uint256); } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } } // File: contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.4.26; /* Contract Registry interface */ contract IContractRegistry { function addressOf(bytes32 _contractName) public view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) public view returns (address); } // File: contracts/utility/ContractRegistryClient.sol pragma solidity 0.4.26; /** * @dev Base contract for ContractRegistry clients */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory"; bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder"; bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { _only(_contractName); _; } // error message binary size optimization function _only(bytes32 _contractName) internal view { require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED"); } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(_registry) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED"); // get the new contract-registry IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY)); // verify that the new contract-registry is different and not zero require(newRegistry != address(registry) && newRegistry != address(0), "ERR_INVALID_REGISTRY"); // verify that the new contract-registry is pointing to a non-zero contract-registry require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY"); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = newRegistry; } /** * @dev restores the previous contract-registry */ function restoreRegistry() public ownerOnly { // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only */ function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly { // change the permission to update the contract-registry onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: contracts/utility/ReentrancyGuard.sol pragma solidity 0.4.26; /** * @dev ReentrancyGuard * * The contract provides protection against re-entrancy - calling a function (directly or * indirectly) from within itself. */ contract ReentrancyGuard { // true while protected code is being executed, false otherwise bool private locked = false; /** * @dev ensures instantiation only by sub-contracts */ constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); locked = true; _; locked = false; } // error message binary size optimization function _protected() internal view { require(!locked, "ERR_REENTRANCY"); } } // File: contracts/utility/TokenHandler.sol pragma solidity 0.4.26; contract TokenHandler { bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)")); /** * @dev executes the ERC20 token's `approve` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _spender approved address * @param _value allowance amount */ function safeApprove(IERC20Token _token, address _spender, uint256 _value) internal { execute(_token, abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value)); } /** * @dev executes the ERC20 token's `transfer` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _to target address * @param _value transfer amount */ function safeTransfer(IERC20Token _token, address _to, uint256 _value) internal { execute(_token, abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value)); } /** * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _from source address * @param _to target address * @param _value transfer amount */ function safeTransferFrom(IERC20Token _token, address _from, address _to, uint256 _value) internal { execute(_token, abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value)); } /** * @dev executes a function on the ERC20 token and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _data data to pass in to the token's contract for execution */ function execute(IERC20Token _token, bytes memory _data) private { uint256[1] memory ret = [uint256(1)]; assembly { let success := call( gas, // gas remaining _token, // destination address 0, // no ether add(_data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(_data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 32 // output length ) if iszero(success) { revert(0, 0) } } require(ret[0] != 0, "ERR_TRANSFER_FAILED"); } } // File: contracts/utility/TokenHolder.sol pragma solidity 0.4.26; /** * @dev We consider every contract to be a 'token holder' since it's currently not possible * for a contract to deny receiving tokens. * * The TokenHolder's contract sole purpose is to provide a safety mechanism that allows * the owner to send tokens that were sent to the contract by mistake back to their sender. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, TokenHandler, Owned, Utils { /** * @dev withdraws tokens held by the contract and sends them to an account * can only be called by the owner * * @param _token ERC20 token contract address * @param _to account to receive the new amount * @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { safeTransfer(_token, _to, _amount); } } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x, "ERR_OVERFLOW"); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y, "ERR_UNDERFLOW"); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y, "ERR_OVERFLOW"); return z; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. * * @param _x dividend * @param _y divisor * * @return quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0, "ERR_DIVIDE_BY_ZERO"); uint256 c = _x / _y; return c; } } // File: contracts/token/interfaces/IEtherToken.sol pragma solidity 0.4.26; /* Ether Token interface */ contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function depositTo(address _to) public payable; function withdrawTo(address _to, uint256 _amount) public; } // File: contracts/token/interfaces/ISmartToken.sol pragma solidity 0.4.26; /* Smart Token interface */ contract ISmartToken is IConverterAnchor, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } // File: contracts/bancorx/interfaces/IBancorX.sol pragma solidity 0.4.26; contract IBancorX { function token() public view returns (IERC20Token) {this;} function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public; function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256); } // File: contracts/BancorNetwork.sol pragma solidity 0.4.26; // interface of older converters for backward compatibility contract ILegacyConverter { function change(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /** * @dev The BancorNetwork contract is the main entry point for Bancor token conversions. * It also allows for the conversion of any token in the Bancor Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the Bancor Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract BancorNetwork is IBancorNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000; uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000; address private constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping (address => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( address indexed _smartToken, address indexed _fromToken, address indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new BancorNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[]) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected rate of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected rate */ function rateByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = _path[i - 2]; IERC20Token anchor = _path[i - 1]; IERC20Token targetToken = _path[i]; converter = IConverter(IConverterAnchor(anchor).owner()); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (targetToken == anchor) { // buy the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseRate(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.add(amount); } else if (sourceToken == anchor) { // sell the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleRate(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the bancor network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(_path[0], IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == 0) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the bancor network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the bancor network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = _path[_path.length - 1]; IBancorX bancorX = IBancorX(addressOf(BANCOR_X)); // verify that the destination token is BNT require(targetToken == addressOf(BNT_TOKEN), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, this, _affiliateAccount, _affiliateFee); // grant BancorX allowance ensureAllowance(targetToken, bancorX, amount); // transfer the resulting amount to BancorX bancorX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the BancorNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * BancorX contract directly by specifying the conversion id * * @param _path conversion path * @param _bancorX address of the BancorX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion(IERC20Token[] _path, IBancorX _bancorX, uint256 _conversionId, uint256 _minReturn, address _beneficiary) public returns (uint256) { // verify that the source token is the BancorX token require(_path[0] == _bancorX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from BancorX contract uint256 amount = _bancorX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, stepData.converter, fromAmount); } // older converter // if the source token is the smart token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != ISmartToken(stepData.anchor)) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert.value(msg.value)(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken(IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount) private { IConverter firstConverter = IConverter(_anchor.owner()); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, this, _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(_sourceToken).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount); else safeTransferFrom(_sourceToken, msg.sender, this, _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion return amount, in the target token * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken(ConversionStep[] _data, uint256 _amount, address _beneficiary) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(targetToken).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData(IERC20Token[] _conversionPath, address _beneficiary, bool _affiliateFeeEnabled) private view returns (ConversionStep[]) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; address bntToken = addressOf(BNT_TOKEN); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(anchor.owner()); IERC20Token targetToken = _conversionPath[i + 2]; // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ // set the converter anchor anchor: anchor, // set the converter converter: converter, // set the source/target tokens sourceToken: _conversionPath[i], targetToken: targetToken, // requires knowledge about the next step, so initialize in the next phase beneficiary: address(0), // set flags isV28OrHigherConverter: isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = this; // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = data[i + 1].converter; // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = this; } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = this; } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { uint256 allowance = _token.allowance(this, _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (address) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { address reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return IERC20Token(ETH_RESERVE_ADDRESS); return IERC20Token(getConverterEtherTokenAddress(_converter)); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using assembly code since older converter versions have different return values function getReturn(address _dest, address _sourceToken, address _targetToken, uint256 _amount) internal view returns (uint256, uint256) { uint256[2] memory ret; bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); assembly { let success := staticcall( gas, // gas remaining _dest, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 64 // output length ) if iszero(success) { revert(0, 0) } } return (ret[0], ret[1]); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using assembly code to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bool success; uint256[1] memory ret; bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); assembly { success := staticcall( 5000, // isV28OrHigher consumes 190 gas, but just for extra safety _converter, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 32 // output length ) } return success && ret[0] != 0; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } }
newer converter transfer the tokens to the converter only if the network contract currently holds the tokens not needed with ETH or if it's the first conversion step older converter if the source token is the smart token, no need to do any transfers as the converter controls it grant allowance for it to transfer the tokens from the network contract pay affiliate-fee if needed
function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) } a predefined conversion path and transfers the result to an account on a different blockchain function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) } function completeXConversion(IERC20Token[] _path, IBancorX _bancorX, uint256 _conversionId, uint256 _minReturn, address _beneficiary) public returns (uint256) } function doConversion( ConversionStep[] _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; if (stepData.isV28OrHigherConverter) { if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, stepData.converter, fromAmount); } else if (stepData.sourceToken != ISmartToken(stepData.anchor)) { ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount); } toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert.value(msg.value)(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } return toAmount;
5,344,544
pragma solidity ^0.4.24; import "./RightsDigitalAssetSpec.sol"; import "./RightsDigitalAssetObject.sol"; import "./DigitalMoneyManager.sol"; import "./DigitalPointManager.sol"; import "./RDDNMarket.sol"; import "./RDDNMarketMoney.sol"; import "./RDDNMarketPoint.sol"; import "./interfaces/IRDDNMarketSales.sol"; import "./utils/RDDNControl.sol"; import "./utils/LinkedIdList.sol"; import "./utils/DoubleLinkedIdList.sol"; import "./modules/FeeModule.sol"; import "openzeppelin-solidity/math/SafeMath.sol"; /// @title RDDNMarketMoney /// @dev Sales controller for markets. contract RDDNMarketSales is IRDDNMarketSales, RDDNControl, FeeModule { using SafeMath for uint256; /*** STORAGE ***/ // Mapping from marketId to specIdList LinkedIdList private specIdList; // Mapping from marketId to objectIdList per spec DoubleLinkedIdList private objectIdList; // Mapping from object id to status whether on sale mapping(uint256 => bool) private objectMarketStatus; // Mapping from object id to market id mapping(uint256 => uint256) private objectMarketId; RDDNMarket private market; RDDNMarketMoney private marketMoney; RDDNMarketPoint private marketPoint; RightsDigitalAssetSpec private assetSpec; RightsDigitalAssetObject private assetObject; DigitalMoneyManager private moneyManager; DigitalPointManager private pointManager; /*** CONSTRUCTOR ***/ constructor ( uint8 _feeRatio, address _marketAddr, address _marketMoneyAddr, address _marketPointAddr, address _assetSpecAddr, address _assetObjectAddr, address _moneyManagerAddr, address _pointManagerAddr ) public FeeModule(_feeRatio) { require(_marketAddr != address(0x0)); require(_marketMoneyAddr != address(0x0)); require(_marketPointAddr != address(0x0)); require(_assetSpecAddr != address(0x0)); require(_assetObjectAddr != address(0x0)); require(_moneyManagerAddr != address(0x0)); require(_pointManagerAddr != address(0x0)); assetSpec = RightsDigitalAssetSpec(_assetSpecAddr); assetObject = RightsDigitalAssetObject(_assetObjectAddr); moneyManager = DigitalMoneyManager(_moneyManagerAddr); pointManager = DigitalPointManager(_pointManagerAddr); market = RDDNMarket(_marketAddr); marketMoney = RDDNMarketMoney(_marketMoneyAddr); marketPoint = RDDNMarketPoint(_marketPointAddr); specIdList = new LinkedIdList(); objectIdList = new DoubleLinkedIdList(); } /*** External Functions ***/ /// @dev Add objectId to market /// @param _marketId marketId /// @param _objectId objectId function addObject( uint256 _marketId, uint256 _objectId ) public whenNotPaused returns (bool) { // check market owner require(market.ownerOf(_marketId) == msg.sender); // check object status whether on sale require(!objectMarketStatus[_objectId]); // check msg.sender approvals require( msg.sender == assetObject.ownerOf(_objectId) || assetObject.isApprovedForAll(assetObject.ownerOf(_objectId), msg.sender) ); // check contract approvals require( this == assetObject.getApproved(_objectId) || assetObject.isApprovedForAll(assetObject.ownerOf(_objectId), this) ); // approve to contract if (this != assetObject.getApproved(_objectId)) { assetObject.approve(this, _objectId); } // add object id uint256 specId = assetObject.specIdOf(_objectId); objectIdList.add(_marketId, specId, _objectId); // update object status objectMarketStatus[_objectId] = true; objectMarketId[_objectId] = _marketId; emit AddObject(msg.sender, _marketId, specId, _objectId); // add spec id if(!specIdList.exists(_marketId, specId)) { specIdList.add(_marketId, specId); emit AddSpec(msg.sender, _marketId, specId); } return true; } /// @dev Remove objectId from market /// @param _marketId marketId /// @param _objectId objectId function removeObject( uint256 _marketId, uint256 _objectId ) public whenNotPaused returns (bool) { require(market.ownerOf(_marketId) == msg.sender); require(assetObject.ownerOf(_objectId) != address(0)); _removeObject(_marketId, _objectId); return true; } /// @dev Purchase object from market /// @param _marketId marketId /// @param _specId specId /// @param _moneyId moneyId /// @param _pointId pointId /// @param _pointValue point value function purchase( uint256 _marketId, uint256 _specId, uint256 _moneyId, uint256 _pointId, uint256 _pointValue ) public whenNotPaused returns (bool) { require(market.isValid(_marketId)); address marketOwner = market.ownerOf(_marketId); // ids check require(marketOwner != address(0)); require(assetSpec.ownerOf(_specId) != address(0)); require(marketMoney.isPayableMoney(_marketId, _moneyId)); require(marketPoint.isPayablePoint(_marketId, _pointId)); // check amount of point require(pointManager.balanceOf(_pointId, msg.sender) >= _pointValue); // calculate amount of point to use uint256 adjustedPointValue = _adjustPointValue(_pointValue, _marketId, _pointId); // calculate amount of money to pay uint256 baseMoneyValue = assetSpec.referenceValueOf(_specId); uint256 feeMoneyValue = marketMoney.exchangedAmountOf( _marketId, _moneyId, feeAmount(baseMoneyValue) ); uint256 afterFeeMoneyValue = marketMoney.exchangedAmountOf( _marketId, _moneyId, afterFeeAmount(baseMoneyValue).sub(adjustedPointValue) ); // check amount of money require(moneyManager.balanceOf(_moneyId, msg.sender) >= feeMoneyValue + afterFeeMoneyValue); // get target objet id to purchase uint256 targetObjectId = _getRandomObjectId(_marketId, _specId); // remove object from market _removeObject(_marketId, targetObjectId); // transfer point from buyer to seller if(adjustedPointValue > 0) { pointManager.forceTransferFrom( msg.sender, marketOwner, _pointValue, _pointId ); } // transfer money from buyer to owner(fee) moneyManager.forceTransferFrom( msg.sender, owner(), feeMoneyValue, _moneyId ); // transfer money from buyer to seller(after fee) moneyManager.forceTransferFrom( msg.sender, marketOwner, afterFeeMoneyValue, _moneyId ); // transfer digital asset from seller to buyer assetObject.transferFrom( marketOwner, msg.sender, targetObjectId ); // mint point to buyer uint256 basePointId = marketPoint.basePointOf(_marketId); pointManager.mint( msg.sender, baseMoneyValue.div(100), basePointId ); emit Purchase( msg.sender, _marketId, _specId, _moneyId, feeMoneyValue + afterFeeMoneyValue, _pointId, _pointValue ); return true; } /// @dev Get specIdList on the market /// @param _marketId marketId /// @return specIdList function specIdsOf(uint256 _marketId) public view returns (uint256[]) { require(market.ownerOf(_marketId) != address(0)); return specIdList.valuesOf(_marketId); } /// @dev Get objectIdList on the market /// @param _marketId marketId /// @return objectIdList function objectIdsOf(uint256 _marketId, uint256 _specId) public view returns (uint256[]) { require(market.ownerOf(_marketId) != address(0)); require(assetSpec.ownerOf(_specId) != address(0)); return objectIdList.valuesOf(_marketId, _specId); } /// @dev Returns whether the specified object id is on sale /// @param _objectId objectId /// @return whether the specified object id is on sale function isOnSale(uint256 _objectId) public view returns(bool) { require(assetObject.ownerOf(_objectId) != address(0)); return objectMarketStatus[_objectId]; } /// @dev the specified market id where the object is sold /// @param _objectId objectId /// @return the specified market id function marketIdOf(uint256 _objectId) public view returns (uint256) { require(isOnSale(_objectId)); return objectMarketId[_objectId]; } /*** INTERNAL FUNCTIONS ***/ /// @dev Remove objectId from market /// @param _marketId marketId /// @param _objectId objectId function _removeObject( uint256 _marketId, uint256 _objectId ) internal { // remove objectId uint256 specId = assetObject.specIdOf(_objectId); objectIdList.remove(_marketId, specId, _objectId); // update object status objectMarketStatus[_objectId] = false; emit RemoveObject(msg.sender, _marketId, specId, _objectId); // remove spec id if(objectIdList.totalOf(_marketId, specId) == 0) { specIdList.remove(_marketId, specId); emit RemoveSpec(msg.sender, _marketId, specId); } } /// @dev Calculate amount of point to pay /// @param _pointValue point value /// @param _marketId marketId /// @param _pointId pointId function _adjustPointValue( uint256 _pointValue, uint256 _marketId, uint256 _pointId ) internal view returns (uint256){ uint256 baseMoneyId = marketMoney.baseMoneyOf(_marketId); uint256 moneyDecimals = uint256(moneyManager.decimalsOf(baseMoneyId)); uint256 pointDecimals = uint256(pointManager.decimalsOf(_pointId)); uint256 pointValue; if(moneyDecimals >= pointDecimals) { pointValue = _pointValue.mul(10 ** (moneyDecimals - pointDecimals)); } else { pointValue = _pointValue.div(10 ** (pointDecimals - moneyDecimals)); } return pointValue .mul(marketPoint.pointRateOf(_marketId, _pointId)) .div(10 ** uint256(marketPoint.rateDecimals())); } /// @dev Get objectId from market randomly /// @param _marketId marketId /// @param _specId specId function _getRandomObjectId( uint256 _marketId, uint256 _specId ) internal view returns (uint256) { uint256 randomIndex = now.mod(objectIdList.totalOf(_marketId, _specId)); return objectIdList.valueOf( _marketId, _specId, randomIndex ); } }
Get objectId from market randomly _marketId marketId _specId specId
function _getRandomObjectId( uint256 _marketId, uint256 _specId ) internal view returns (uint256) { uint256 randomIndex = now.mod(objectIdList.totalOf(_marketId, _specId)); return objectIdList.valueOf( _marketId, _specId, randomIndex ); }
12,876,280
pragma solidity 0.4.18; /** * Math operations with safety checks */ contract BaseSafeMath { /* standard uint256 functions */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert( b > 0 ); uint256 c = a / b; return c; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions */ function madd(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; assert(c >= a); return c; } function msub(uint128 a, uint128 b) internal pure returns (uint128) { assert(b <= a); return a - b; } function mmul(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a * b; assert(a == 0 || c / a == b); return c; } function mdiv(uint128 a, uint128 b) internal pure returns (uint128) { assert( b > 0 ); uint128 c = a / b; return c; } function mmin(uint128 x, uint128 y) internal pure returns (uint128 z) { return x <= y ? x : y; } function mmax(uint128 x, uint128 y) internal pure returns (uint128 z) { return x >= y ? x : y; } /* uint64 functions */ function miadd(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; assert(c >= a); return c; } function misub(uint64 a, uint64 b) internal pure returns (uint64) { assert(b <= a); return a - b; } function mimul(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a * b; assert(a == 0 || c / a == b); return c; } function midiv(uint64 a, uint64 b) internal pure returns (uint64) { assert( b > 0 ); uint64 c = a / b; return c; } function mimin(uint64 x, uint64 y) internal pure returns (uint64 z) { return x <= y ? x : y; } function mimax(uint64 x, uint64 y) internal pure returns (uint64 z) { return x >= y ? x : y; } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract BaseERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowed; // This generates 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); /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal; /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success); /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success); } /** * @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 publishOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { publishOwner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == publishOwner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(publishOwner, newOwner); publishOwner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract LightCoinToken is BaseERC20, BaseSafeMath, Pausable { //The solidity created time address public owner; address public lockOwner; uint256 public lockAmount ; uint256 public startTime ; function LightCoinToken() public { owner = 0x55ae8974743DB03761356D703A9cfc0F24045ebb; lockOwner = 0x07d4C8CC52BB7c4AB46A1A65DCEEdC1ab29aBDd6; startTime = 1515686400; name = "Lightcoin"; symbol = "Light"; decimals = 8; ///totalSupply = 21000000000000000000; totalSupply = 2.1e19; balanceOf[owner] = totalSupply * 90 /100; lockAmount = totalSupply * 10 / 100 ; Transfer(address(0), owner, balanceOf[owner]); } /// @param _owner The address from which the balance will be retrieved /// @return The balance function getBalanceOf(address _owner) public constant returns (uint256 balance) { return balanceOf[_owner]; } function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Save this for an assertion in the future uint previousBalances = add(balanceOf[_from], balanceOf[_to]); // Subtract from the sender balanceOf[_from] = sub(balanceOf[_from], _value); // Add the same to the recipient balanceOf[_to] = add(balanceOf[_to], _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(add(balanceOf[_from], balanceOf[_to]) == previousBalances); Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) { // Check allowance allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function releaseToken() public{ uint256 releaseBegin = add(startTime, 2 * 365 * 86400); require(now >= releaseBegin ); uint256 interval = sub(now, releaseBegin); uint256 i = div(interval, (0.5 * 365 * 86400)); if (i > 3) { i = 3; } uint256 releasevalue = div(totalSupply, 40); uint256 remainInterval = sub(3, i); require(lockAmount > mul(remainInterval, releasevalue)); lockAmount = sub(lockAmount, releasevalue); balanceOf[lockOwner] = add( balanceOf[lockOwner], releasevalue); Transfer(address(0), lockOwner, releasevalue); } function () public payable{ revert(); } }
Prevent transfer to 0x0 address. Use burn() instead Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
function _transfer(address _from, address _to, uint256 _value) internal { require(_to != 0x0); uint previousBalances = add(balanceOf[_from], balanceOf[_to]); balanceOf[_from] = sub(balanceOf[_from], _value); balanceOf[_to] = add(balanceOf[_to], _value); assert(add(balanceOf[_from], balanceOf[_to]) == previousBalances); Transfer(_from, _to, _value); }
7,947,537
./partial_match/97/0xc715D88DC2824dF62ebD88Ca269271282A423912/sources/TokenineERC20.sol
See {ERC20-_beforeTokenTransfer}. Requirements: - the contract must not be paused./
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } bool private _paused;
11,354,345
//SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract RingsNFT is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; event Mint( address indexed _to, uint256 indexed _tokenId, uint256 _tokensCount, uint256 _value ); address payable public ownerAddress; address public admin; string public projectBaseURI = 'https://andrewfernandez-art-api.herokuapp.com/projects/0/tokens/metadata/'; string public script; bool public active = false; uint256 public maxPurchaseable = 1; uint256 public maxTokens = 999; uint256 public tokensCount; uint256 public pricePerTokenInWei = 0; mapping(uint256 => bytes32[]) internal tokenIdToHashes; // what tokens belong to what hashes modifier onlyValidTokenId(uint256 _tokenId) { require(_exists(_tokenId), "Token ID does not exist"); _; } //only allow this if the sender is an admin modifier onlyAdmin() { require(msg.sender == admin, "Only admin"); _; } constructor() ERC721("RingsNFT", "RINGS") { admin = msg.sender; // set admin to the creator ownerAddress = payable(msg.sender); //set the payable address to the creator } function mint(uint256 tokenQuantity) external payable { require(!_isContract(msg.sender), "Contract minting is not allowed"); // dont let contracts mints require(tokenQuantity > 0, "You must mint at least one."); // gotta mint atleast 1 require(tokenQuantity <= maxPurchaseable, "You are minting too many at once!"); // minting more than max allowed // don't allow overminting the max invocations require(totalSupply() + tokenQuantity <= maxTokens, "The amount you are trying to mint exceeds the max supply of 999."); //the project must be active or its the admin require(active || msg.sender == admin, "Project must exist and be active"); //make sure the amount per token is corrent in the message value require(pricePerTokenInWei * tokenQuantity <= msg.value, "Incorrect Ether value."); //loop through how many the user wants and call mint of the specific project for (uint256 i = 0; i < tokenQuantity; i++) { //call the minttoken method for the project _mintToken(msg.sender); } } // mint function take the to address , project, and returns a token id...only internal method function _mintToken(address _to) internal returns (uint256 _tokenId) { //set the token id ..project 0 * million + token id ex: 0*1M + 2045 = 2045 for project 0 uint256 tokenIdToBe = tokensCount; // update the internal count of invocations tokensCount = tokensCount.add(1); //create a hash based on the project id invocations number bytes32 hash = keccak256(abi.encodePacked(tokensCount, block.number.add(1), msg.sender)); //add that hash to the tokenIdToBe hash tokenIdToHashes[tokenIdToBe].push(hash); //call the real safemint to create the token _safeMint(_to, tokenIdToBe); // emit the mint event emit Mint(_to, tokenIdToBe, tokensCount, pricePerTokenInWei); // return the token ID return tokenIdToBe; } //gets the token hash for the script for the art function showTokenHashes(uint _tokenId) public view returns (bytes32[] memory){ return tokenIdToHashes[_tokenId]; } // update the project price function updatePricePerTokenInWei(uint256 _pricePerTokenInWei) onlyAdmin external { pricePerTokenInWei = _pricePerTokenInWei; } //get the tokenURI for the project function tokenURI(uint256 _tokenId) public view virtual override onlyValidTokenId(_tokenId) returns (string memory) { return string(abi.encodePacked(projectBaseURI, Strings.toString(_tokenId))); } //set the scripts function updateScript(string memory _script) onlyAdmin external { require(tokensCount == 0, "Can not switch after a 1 is minted."); script = _script; } //toggle as active function toggleIsActive() public onlyAdmin { active = !active; } //update project URI function updateProjectBaseURI(string memory _projectBaseURI) public onlyAdmin { projectBaseURI = _projectBaseURI; } //transfer ownership of project to a new owner function transferOwnership(address newOwner) public override onlyOwner { //make sure its not an empty address require(newOwner != address(0), "Ownable: new owner is the zero address"); //set the new owner to admin admin = newOwner; //update the payout address so its the new owner ownerAddress = payable(newOwner); //call the loaded transfer method super.transferOwnership(newOwner); } function _isContract(address _addr) internal view returns (bool) { uint32 _size; assembly { _size:= extcodesize(_addr) } return (_size > 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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); }
mint function take the to address , project, and returns a token id...only internal methodset the token id ..project 0 million + token id ex: 01M + 2045 = 2045 for project 0 update the internal count of invocationscreate a hash based on the project id invocations numberadd that hash to the tokenIdToBe hashcall the real safemint to create the token emit the mint event return the token ID
function _mintToken(address _to) internal returns (uint256 _tokenId) { uint256 tokenIdToBe = tokensCount; tokensCount = tokensCount.add(1); bytes32 hash = keccak256(abi.encodePacked(tokensCount, block.number.add(1), msg.sender)); tokenIdToHashes[tokenIdToBe].push(hash); _safeMint(_to, tokenIdToBe); emit Mint(_to, tokenIdToBe, tokensCount, pricePerTokenInWei); return tokenIdToBe; }
521,533
/** *Submitted for verification at Etherscan.io on 2020-02-03 */ pragma solidity ^0.5.12; /** * @dev Simplified contract of a `../Swapper.sol` */ contract SwapperLike { function fromDaiToBTU(address, uint256) external; } /** * @dev Simplified contract of a VatLike * For full implementation please see MakerDAO's repo at <https://github.com/makerdao/dss> */ contract VatLike { function hope(address) external; } /** * @dev Simplified contract of a PotLike * For full implementation please see MakerDAO's repo at <https://github.com/makerdao/dss> */ contract PotLike { function chi() external view returns (uint256); function rho() external view returns (uint256); function dsr() external view returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } /** * @dev Simplified contract of a DaiJoin * For full implementation please see MakerDAO's repo at <https://github.com/makerdao/dss> */ contract JoinLike { function join(address, uint256) external; function exit(address, uint256) external; } /** * @dev Simplified contract of a ERC20 Token */ contract ERC20Like { function transferFrom(address, address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function allowance(address, address) 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); } library RayMath { uint256 internal constant ONE_RAY = 10**27; function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "Bdai: overflow"); return c; } function sub(uint256 a, uint256 b, string memory errMsg) internal pure returns (uint256) { require(b <= a, errMsg); return a - b; } function subOrZero(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { return uint256(0); } else { return a - b; } } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "bDai: multiplication overflow"); return c; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / ONE_RAY; } /** * @dev Warning : result is rounded toward zero */ function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "bDai: division by 0"); return mul(a, ONE_RAY) / b; } /** * @dev do division with rouding up */ function rdivup(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, ONE_RAY), sub(b, 1, "bDai: division by 0")) / b; } } /** * @dev Implementation of the bDAI ERC20 token * * This contracts aims to take `amount` DAI, subscribes it to the DSR program and * gives back `amount` of bDAI. User can then earn interests on these bDAI in BTU * * To have bDAI user needs to call join or joinFor * claim and claimFor are used to be get back interests in BTU * exit and exitFor are aimed to claim back the user's DAI */ contract Bdai is IERC20 { using RayMath for uint256; bool public live; uint8 public constant decimals = 18; uint256 public totalSupply; string public constant name = "BTU Incentivized DAI"; string public constant symbol = "bDAI"; string public constant version = "1"; mapping(address => uint256) private _balances; mapping(address => uint256) private _pies; mapping(address => uint256) private _nonces; mapping(address => mapping(address => uint256)) private _allowances; ERC20Like public dai; JoinLike public daiJoin; PotLike public pot; VatLike public vat; SwapperLike public swapper; address public owner; bytes32 public DOMAIN_SEPARATOR; //EIP712 domain //keccak256 "Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)" bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; //keccak256 "ClaimFor(address holder,address spender,uint256 nonce,uint256 expiry,address dest)" bytes32 public constant CLAIM_TYPEHASH = 0xcbd06f2e482e52538ba0a2e3b1ec074c1ff826895448b9cf7b33c0abbbe904b3; //keccak256 "ExitFor(address holder,address spender,uint256 nonce,uint256 expiry,uint256 amount)" bytes32 public constant EXIT_TYPEHASH = 0x703d2576480f8b8746c2232693aae93ab2bda9c8b68427bce6eff0c6238807ed; /** * @dev Sets the external MakerDAO's contract address. All of these values are immutable. * Authorises these contracts to play with DAI owned by `this` */ constructor( address dai_, address daiJoin_, address pot_, address vat_, address swapper_, uint256 chainId_ ) public { owner = msg.sender; live = true; dai = ERC20Like(dai_); daiJoin = JoinLike(daiJoin_); pot = PotLike(pot_); vat = VatLike(vat_); swapper = SwapperLike(swapper_); vat.hope(daiJoin_); vat.hope(pot_); dai.approve(daiJoin_, uint256(-1)); dai.approve(swapper_, uint256(-1)); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes(version)), chainId_, address(this) ) ); } /** * @dev Returns the amount of bDAI owned by `account`. */ function balanceOf(address account) public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _balances[account]; } /** * @dev Transfers `amount` of bDAI from `sender` to `recipient` * Before the transfer, `sender` earns interrests on its bDAI * * Requirements : * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. * * Emits {Transfer} event */ function transfer(address recipient, uint256 amount) public //inject PUBLIC FUNC TO EXTERNAL returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev Returns the pie owned by `account` on the DSR contract (e.g. pot.sol from MakerDAO). */ function pieOf(address account) public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _pies[account]; } /** * @dev Returns the last recorded `chi` from the dsr contract */ function chi() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return pot.chi(); } /** * @dev Returns the last recorded `rho` from the dsr contract */ function rho() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return pot.rho(); } /** * @dev Returns the last recorded `dsr` from the dsr contract */ function dsr() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return pot.dsr(); } /** * @dev Returns the amount of bDAI which `spender` can take from `tokenOwner` account */ function allowance(address tokenOwner, address spender) public //inject PUBLIC FUNC TO EXTERNAL view returns (uint256) { return _allowances[tokenOwner][spender]; } /** * @dev Sets an allowance of `amount` for `spender` over the caller's bDAI * * Emits {Approval} event */ function approve(address spender, uint256 amount) public returns (bool) { //inject PUBLIC FUNC TO EXTERNAL require(spender != address(0), "Bdai: approve to 0x0"); _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @dev Transfers `amount` of bDAI from `sender` to `recipient` * Before the transfer, `sender` earns interrests on its bDAI * Updates allowance if not set to MAX_UINT256 * * Requirements : * - `sender`cannot be the zero address. * - `recipient` cannot be the zero address. * - the caller must have an allowance of at least `amount`. * - `sender` must have at least `amount` of token * * Emits {Transfer} event * Emits an {Approval} event indicating the updated allowance */ function transferFrom(address sender, address recipient, uint256 amount) public //inject PUBLIC FUNC TO EXTERNAL returns (bool) { _allow(sender, msg.sender, amount); _transfer(sender, recipient, amount); return true; } /** * @dev Takes `amount` of DAI (in wad) from the caller and subscribes it to the dsr * Mints `amount` of bDAI for the caller * * Requirements : * - the caller must have at least `amount` of DAI. * * Emits {Transfer} event */ function join(uint256 amount) public { //inject PUBLIC FUNC TO EXTERNAL _join(msg.sender, amount); } /** * @dev Takes `amount` of DAI (in wad) from the caller and subscribes it to the dsr * Mints `amount` of bDAI for `dest` (e.g. DAI are taken from caller and bDAI are sent to `dest`) * * Requirements : * - the caller must have at least `amount` of DAI. * - `dest` cannot be zero address * * Emits {Transfer} event */ function joinFor(address dest, uint256 amount) public { //inject PUBLIC FUNC TO EXTERNAL require(dest != address(0), "bDai: dest cannot be 0x0"); _join(dest, amount); } /** * @dev Recalculates caller's `pie` to fit with its bDAI * Converts interrests to BTU and sends it to caller's address */ function claim() public { //inject PUBLIC FUNC TO EXTERNAL _claim(msg.sender, msg.sender); } /** * @dev Recalculates caller's `pie` to fit with its bDAI * Converts interrests to BTU and sends it to `dest` address * * Requirements : * - `dest` cannot be the zero address */ function claim(address dest) public { //inject PUBLIC FUNC TO EXTERNAL require(dest != address(0), "bDai: dest cannot be 0x0"); _claim(msg.sender, dest); } /** * @dev Takes `amount` of bDAI and returns `amount` of DAI * Claims interest * Burns `amount` of bDAI * * Requirements : * - the caller must have at least `amount` of bDAI. * * Emits {Transfer} event */ function exit(uint256 amount) public { //inject PUBLIC FUNC TO EXTERNAL _exit(msg.sender, amount); } /** * @dev Transfers `amounts` of bDAI from caller to `recipients` * Before the transfer, caller earns interrests on its bDAI * * Requirements : * - `recipients` cannot contain the zero address. * - the caller must have a balance of at least `total(amounts)`. * * Emits {Transfer} event */ function transfer(address[] memory recipients, uint256[] memory amounts) public returns (bool) { _transfer(msg.sender, recipients, amounts); return true; } /** * @dev Transfers `amounts` of bDAI from caller to `recipients` * Before the transfer, caller earns interrests on its bDAI * * Requirements : * - `sender`cannot be the zero address. * - `recipients` cannot contain the zero address. * - the caller must have an allowance of at least `total(amounts)`. * - `sender` must have a balance of at least `total(amounts)`. * * Emits {Transfer} event * Emits an {Approval} event indicating the updated allowance */ function transferFrom( address sender, address[] memory recipients, uint256[] memory amounts ) public returns (bool) { uint256 total; for (uint256 i; i < recipients.length; ++i) { total = total.add(amounts[i]); } _allow(sender, msg.sender, total); _transfer(sender, recipients, amounts); return true; } /** * @dev Returns the noce ofe `account` */ function nonces(address account) public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _nonces[account]; } /** * @dev Sets an allowance of `MAX_UINT256` for `spender` over the holder's bDAI if `allowaed` set to `true` * * Requiremets: * - `holder` cannot be the zero address * - `spender` cannot be the zero address * - `nonce` must be actual nonce of `holder` + 1 * - `expiry` must be zero (for infinite validity) or lower than `now` if not null * - `v`, `r`, `s` must contain the permit message signed by `holder` * * Emits {Approval} event */ function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public { //inject PUBLIC FUNC TO EXTERNAL require(holder != address(0), "bDai: approve from 0x0"); require(spender != address(0), "bDai: approve to 0x0"); require(expiry == 0 || now <= expiry, "bDai: permit-expired"); require(nonce == _nonces[holder]++, "bDai: invalid-nonce"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed ) ) ) ); require(holder == ecrecover(digest, v, r, s), "bDai: invalid-permit"); uint256 amount = allowed ? uint256(-1) : 0; _allowances[holder][spender] = amount; emit Approval(holder, spender, amount); } /** * @dev Recalculates `account`'s `pie` to fit with its bDAI * Converts interrests to BTU and sends it to `dest` address * * Requirements : * - the caller must have an allowance >= of the `account`'s balance * - `dest` cannot be the zero address */ function claimFor( address holder, uint256 nonce, uint256 expiry, address dest, uint8 v, bytes32 r, bytes32 s ) public { //inject PUBLIC FUNC TO EXTERNAL require(dest != address(0), "bDai: dest cannot be 0x0"); require(holder != address(0), "bDai: claim from 0x0"); require(expiry == 0 || now <= expiry, "bDai: permit-expired"); require(nonce == _nonces[holder]++, "bDai: invalid-nonce"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( CLAIM_TYPEHASH, holder, msg.sender, nonce, expiry, dest ) ) ) ); require(holder == ecrecover(digest, v, r, s), "bDai: invalid-permit"); _claim(holder, dest); } /** * @dev Takes `amount` of bDAI and returns `amount` of DAI in the name of `account` * Claims interest * Burns `amount` of bDAI * * Requirements : * - `holder` must have at least `amount` of bDAI. * - `holder` cannot be the zero address * - `nonce` must be actual nonce of `holder` + 1 * - `expiry` must be zero (for infinite validity) or lower than `now` if not null * - `v`, `r`, `s` must contain the permit message signed by `holder` * * Emits {Transfer} event */ function exitFor( address holder, uint256 nonce, uint256 expiry, uint256 amount, uint8 v, bytes32 r, bytes32 s ) public { //inject PUBLIC FUNC TO EXTERNAL require(holder != address(0), "bDai: exit from 0x0"); require(expiry == 0 || now <= expiry, "bDai: permit-expired"); require(nonce == _nonces[holder]++, "bDai: invalid-nonce"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( EXIT_TYPEHASH, holder, msg.sender, nonce, expiry, amount ) ) ) ); require(holder == ecrecover(digest, v, r, s), "bDai: invalid-permit"); _exit(holder, amount); } /** * @dev only callers with address equals to `owner` can call functions with this modifier */ modifier onlyOwner() { require(msg.sender == owner, "bDai: op not allowed"); _; } /** * @dev Changes the contract owner from `owner` to `owner_` * * Requirements : * - the caller must be the actual contract `owner` * - `owner_` cannot be the zero address * */ function setOwner(address owner_) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL require(owner_ != address(0), "bDai: owner cannot be 0x0"); owner = owner_; } /** * @dev Changes the `live` params, if set to `false` join functionnality is blocked * * Requirements : * - the caller must be the actual contract `owner` * */ function freeze(bool freeze_) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL live = !freeze_; } /** * @dev Changes the `swapper` contract * * Requirements : * - the caller must be the actual contract `owner` * - `swapper_` cannot be the zero address * */ function setSwapper(address swapper_) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL require(swapper_ != address(0), "bDai: cannot set to 0x0"); address oldSwapper = address(swapper); swapper = SwapperLike(swapper_); dai.approve(oldSwapper, uint256(0)); dai.approve(swapper_, uint256(-1)); } /** * @dev Returns the actual `chi` from the DSR (e.g. call `pot.drip()` if needed) */ function _chi() internal returns (uint256) { return now > pot.rho() ? pot.drip() : pot.chi(); } /** * @dev Updates the allowance of `caller` over `sender` for a specified `amount` * Emits an {Approval} event indicating the updated allowance */ function _allow(address sender, address caller, uint256 amount) internal { uint256 a = _allowances[sender][caller]; require(a > 0, "bDAI: bad allowance"); if (a != uint256(-1)) { _allowances[sender][caller] = a.sub(amount, "bDAI: bad allowance"); emit Approval(sender, caller, _allowances[sender][caller]); } } /** * @dev Transfers `amount` of bDAI from `sender` to `recipient` * Before the transfer, `sender` earns interrests on its bDAI * * Requirements : * - `sender`cannot be the zero address. * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. * * Emits {Transfer} event */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "Bdai: transfer from 0x0"); require(recipient != address(0), "Bdai: transfer to 0x0"); uint256 c = _chi(); uint256 senderBalance = _balances[sender]; uint256 oldSenderPie = _pies[sender]; uint256 tmp = senderBalance.rdivup(c); //Pie reseted uint256 pieToClaim = oldSenderPie.subOrZero(tmp); uint256 pieToBeTransfered = amount.rdivup(c); _balances[sender] = senderBalance.sub( amount, "bDai: not enougth funds" ); _balances[recipient] = _balances[recipient].add(amount); tmp = pieToClaim.add(pieToBeTransfered); if (tmp > oldSenderPie) { _pies[sender] = 0; _pies[recipient] = _pies[recipient].add(oldSenderPie); } else { _pies[sender] = oldSenderPie - tmp; _pies[recipient] = _pies[recipient].add(pieToBeTransfered); } if (pieToClaim > 0) { uint256 claimedToken = pieToClaim.rmul(c); pot.exit(pieToClaim); daiJoin.exit(address(this), claimedToken); swapper.fromDaiToBTU(sender, claimedToken); } emit Transfer(sender, recipient, amount); } /** * @dev Transfers `amounts` of bDAI from caller to `recipients` * Before the transfer, caller earns interrests on its bDAI * * Requirements : * - `sender`cannot be the zero address. * - `recipients` cannot contain the zero address. * - the caller must have an allowance of at least `total(amounts)`. * - `sender` must have a balance of at least `total(amounts)`. * * Emits {Transfer} event */ function _transfer( address sender, address[] memory recipients, uint256[] memory amounts ) internal { require(sender != address(0), "Bdai: transfer from 0x0"); uint256 c = _chi(); uint256 senderBalance = _balances[sender]; uint256 oldSenderPie = _pies[sender]; uint256 tmp = senderBalance.rdivup(c); //Pie reseted uint256 pieToClaim = oldSenderPie.subOrZero(tmp); uint256 pieToBeTransfered; uint256 total; uint256 totalPie = oldSenderPie; for (uint256 i; i < recipients.length; ++i) { require(recipients[i] != address(0), "Bdai: transfer to 0x0"); total = total.add(amounts[i]); pieToBeTransfered = amounts[i].rdivup(c); _balances[recipients[i]] = _balances[recipients[i]].add(amounts[i]); tmp = pieToClaim.add(pieToBeTransfered); if (tmp > oldSenderPie) { totalPie = 0; _pies[recipients[i]] = _pies[recipients[i]].add(oldSenderPie); } else { totalPie = oldSenderPie - tmp; _pies[recipients[i]] = _pies[recipients[i]].add( pieToBeTransfered ); } emit Transfer(sender, recipients[i], amounts[i]); } _balances[sender] = senderBalance.sub(total, "bDai: not enougth funds"); _pies[sender] = totalPie; if (pieToClaim > 0) { uint256 claimedToken = pieToClaim.rmul(c); pot.exit(pieToClaim); daiJoin.exit(address(this), claimedToken); swapper.fromDaiToBTU(sender, claimedToken); } } /** * @dev Takes `amount` of DAI (in wad) from the caller and subscribes it to the dsr * Mints `amount` of bDAI for `dest` (e.g. DAI are taken from caller and bDAI are sent to `dest`) * * Requirements : * - the caller must have at least `amount` of DAI. * * Emits {Transfer} event */ function _join(address dest, uint256 amount) internal { require(live, "bDai: system is frozen"); uint256 c = _chi(); uint256 pie = amount.rdiv(c); totalSupply = totalSupply.add(amount); _balances[dest] = _balances[dest].add(amount); _pies[dest] = _pies[dest].add(pie); dai.transferFrom(msg.sender, address(this), amount); daiJoin.join(address(this), amount); pot.join(pie); emit Transfer(address(0), dest, amount); } /** * @dev Recalculates `account`'s `pie` to fit with its bDAI * Sends BTU to `dest` address * Converts interrests to BTU and sends it to caller's address */ function _claim(address account, address dest) internal { uint256 c = _chi(); uint256 newPie = _balances[account].rdivup(c); uint256 pieDiff = _pies[account].subOrZero(newPie); if (pieDiff > 0) { uint256 exitedTokens = pieDiff.rmul(c); _pies[account] = newPie; pot.exit(pieDiff); daiJoin.exit(address(this), exitedTokens); swapper.fromDaiToBTU(dest, exitedTokens); } } /** * @dev Takes `amount` of bDAI and returns `amount` of DAI in the name of `account` * Claims interest * Burns `amount` of bDAI * * Requirements : * - `amount` cannot be zero * - `account` must have at least `amount` of bDAI. * - the caller must have an allowance of at least `amount` over the `account` address * * Emits {Transfer} event */ function _exit(address account, uint256 amount) internal { require(amount > 0, "bDai : zero amount"); uint256 c = _chi(); uint256 bal2 = _balances[account].sub( amount, "bDai: not enougth funds" ); uint256 pie2 = bal2.rdiv(c); uint256 pieDiff = _pies[account].sub(pie2, "bDai: not enougth funds"); uint256 totalDai = pieDiff.rmul(c); uint256 interestToken = totalDai.subOrZero(amount); _balances[account] = bal2; totalSupply = totalSupply.sub(amount, "bDai: totalSupply underflow"); _pies[account] = pie2; pot.exit(pieDiff); daiJoin.exit(address(this), totalDai); dai.transfer(account, amount); if (interestToken > 0) { swapper.fromDaiToBTU(account, interestToken); } emit Transfer(account, address(0), amount); } }
inject PUBLIC FUNC TO EXTERNAL
function nonces(address account) public view returns (uint256) {
1,787,570
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract MogulMarketplaceERC721 is ERC721Holder, AccessControl, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); address payable public treasuryWallet; IERC20 stars; uint256 public nextListingId; uint256 public nextAuctionId; uint256 public starsFeeBasisPoint; //4 decimals, applies to auctions and listings. Fees collected are held in contract uint256 public ethFeeBasisPoint; //4 decimals, applies to auctions and listings. Fees collected are held in contract uint256 public adminEth; //Total Ether available for withdrawal uint256 public adminStars; //Total Stars available for withdrawal uint256 private highestCommissionBasisPoint; //Used to determine what the maximum fee uint256 public starsAvailableForCashBack; //STARS available for cashback uint256 public starsCashBackBasisPoint = 500; bool public starsAllowed = true; bool public ethAllowed = true; struct Listing { address payable seller; address tokenAddress; uint256 tokenId; uint256 starsPrice; uint256 ethPrice; bool isStarsListing; bool isEthListing; } struct Auction { address payable seller; address tokenAddress; uint256 tokenId; uint256 startingPrice; uint256 startTime; uint256 endTime; uint256 reservePrice; bool isStarsAuction; Bid highestBid; } struct Bid { address payable bidder; uint256 amount; } struct TokenCommissionInfo { address payable artistAddress; uint256 commissionBasisPoint; //4 decimals } EnumerableSet.AddressSet private mogulNFTs; EnumerableSet.UintSet private listingIds; EnumerableSet.UintSet private auctionIds; mapping(uint256 => Listing) public listings; mapping(uint256 => Auction) public auctions; mapping(address => TokenCommissionInfo) public commissions; //NFT address to TokenCommissionInfo event ListingCreated( uint256 listingId, address seller, address tokenAddress, uint256 tokenId, uint256 tokenAmount, uint256 starsPrice, uint256 ethPrice, bool isStarsListing, bool isEthListing ); event ListingCancelled(uint256 listingId); event ListingPriceChanged( uint256 listingId, uint256 newPrice, bool isStarsPrice ); event AuctionCreated( uint256 auctionId, address seller, address tokenAddress, uint256 tokenId, uint256 tokenAmount, uint256 startingPrice, uint256 startTime, uint256 endTime, uint256 reservePrice, bool isStarsAuction ); event SaleMade( address buyer, uint256 listingId, uint256 amount, bool isStarsPurchase ); event BidPlaced( address bidder, uint256 auctionId, uint256 amount, bool isStarsBid ); event AuctionClaimed(address winner, uint256 auctionId); event AuctionCancelled(uint256 auctionId); event AuctionReservePriceChanged( uint256 auctionId, uint256 newReservePrice ); event TokenCommissionAdded( address tokenAddress, address artistAddress, uint256 commissionBasisPoint ); event StarsCashBackBasisPointSet(uint256 newStarsCashBackBasisPoint); event StarsFeeBasisPointSet(uint256 newStarsFeeBasisPoint); event EthFeeBasisPointSet(uint256 newEthFeeBasisPoint); modifier onlyAdmin { require(hasRole(ROLE_ADMIN, msg.sender), "Sender is not admin"); _; } modifier sellerOrAdmin(address seller) { require( msg.sender == seller || hasRole(ROLE_ADMIN, msg.sender), "Sender is not seller or admin" ); _; } /** * @dev Stores the Stars contract, and allows users with the admin role to * grant/revoke the admin role from other users. Stores treasury wallet. * * Params: * starsAddress: the address of the Stars contract * _admin: address of the first admin * _treasuryWallet: address of treasury wallet * _mogulNFTAddress: address of a Mogul NFT */ constructor( address starsAddress, address _admin, address payable _treasuryWallet, address _mogulNFTAddress ) { require( _treasuryWallet != address(0), "Treasury wallet cannot be 0 address" ); _setupRole(ROLE_ADMIN, _admin); _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); treasuryWallet = _treasuryWallet; stars = IERC20(starsAddress); mogulNFTs.add(_mogulNFTAddress); } //Get number of listings function getNumListings() external view returns (uint256) { return listingIds.length(); } /** * @dev Get listing ID at index * * Params: * indices: indices of IDs */ function getListingIds(uint256[] memory indices) external view returns (uint256[] memory) { uint256[] memory output = new uint256[](indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = listingIds.at(indices[i]); } return output; } /** * @dev Get listing correlated to index * * Params: * indices: indices of IDs */ function getListingsAtIndices(uint256[] memory indices) external view returns (Listing[] memory) { Listing[] memory output = new Listing[](indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = listings[listingIds.at(indices[i])]; } return output; } //Get number of auctions function getNumAuctions() external view returns (uint256) { return auctionIds.length(); } /** * @dev Get auction ID at index * * Params: * indices: indices of IDs */ function getAuctionIds(uint256[] memory indices) external view returns (uint256[] memory) { uint256[] memory output = new uint256[](indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = auctionIds.at(indices[i]); } return output; } /** * @dev Get auction correlated to index * * Params: * indices: indices of IDs */ function getAuctionsAtIndices(uint256[] memory indices) external view returns (Auction[] memory) { Auction[] memory output = new Auction[](indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = auctions[auctionIds.at(indices[i])]; } return output; } /** * @dev Create a new listing * * Params: * tokenAddress: address of token to list * tokenId: id of token * starsPrice: listing STARS price * ethPrice: listing ETH price * isStarsListing: whether or not the listing can be sold for STARS * isEthListing: whether or not the listing can be sold for ETH * * Requirements: * - Listings of given currencies are allowed * - Price of given currencies are not 0 * - mogulNFTs contains tokenAddress */ function createListing( address tokenAddress, uint256 tokenId, uint256 tokenAmount, uint256 starsPrice, uint256 ethPrice, bool isStarsListing, bool isEthListing ) public nonReentrant() { require( mogulNFTs.contains(tokenAddress), "Only Mogul NFTs can be listed" ); if (isStarsListing) { require(starsPrice != 0, "Price cannot be 0"); } if (isEthListing) { require(ethPrice != 0, "Price cannot be 0"); } if (isStarsListing) { require(starsAllowed, "STARS listings are not allowed"); } if (isEthListing) { require(ethAllowed, "ETH listings are not allowed"); } IERC721 token = IERC721(tokenAddress); token.safeTransferFrom(msg.sender, address(this), tokenId); uint256 listingId = generateListingId(); listings[listingId] = Listing( payable(msg.sender), tokenAddress, tokenId, starsPrice, ethPrice, isStarsListing, isEthListing ); listingIds.add(listingId); emit ListingCreated( listingId, msg.sender, tokenAddress, tokenId, 1, starsPrice, ethPrice, isStarsListing, isEthListing ); } /** * @dev Batch create new listings * * Params: * tokenAddresses: addresses of tokens to list * tokenIds: id of each token * starsPrices: STARS price of each listing * ethPrices: ETH price of each listing * areStarsListings: whether or not each listing can be sold for Stars * areEthListings: whether or not each listing can be sold for ETH * * Requirements: * - All inputs are the same length */ function batchCreateListings( address[] calldata tokenAddresses, uint256[] calldata tokenIds, uint256[] calldata starsPrices, uint256[] calldata ethPrices, bool[] memory areStarsListings, bool[] memory areEthListings ) external onlyAdmin { require( tokenAddresses.length == tokenIds.length && tokenIds.length == starsPrices.length && starsPrices.length == ethPrices.length && ethPrices.length == areStarsListings.length && areStarsListings.length == areEthListings.length, "Incorrect input lengths" ); for (uint256 i = 0; i < tokenAddresses.length; i++) { createListing( tokenAddresses[i], tokenIds[i], 1, starsPrices[i], ethPrices[i], areStarsListings[i], areEthListings[i] ); } } /** * @dev Cancel a listing * * Params: * listingId: listing ID */ function cancelListing(uint256 listingId) public sellerOrAdmin(listings[listingId].seller) nonReentrant() { require(listingIds.contains(listingId), "Listing does not exist"); Listing storage listing = listings[listingId]; listingIds.remove(listingId); IERC721 token = IERC721(listing.tokenAddress); token.safeTransferFrom(address(this), listing.seller, listing.tokenId); emit ListingCancelled(listingId); } function batchCancelListing(uint256[] calldata _listingIds) external onlyAdmin { for (uint256 i = 0; i < _listingIds.length; i++) { cancelListing(_listingIds[i]); } } /** * @dev Change price of a listing * * Params: * listingId: listing ID * newPrice: price to change to * isStarsPrice: whether or not the price being changed is in STARS * * Requirements: * - newPrice is not 0 */ function changeListingPrice( uint256 listingId, uint256 newPrice, bool isStarsPrice ) external sellerOrAdmin(listings[listingId].seller) { require(listingIds.contains(listingId), "Listing does not exist."); require(newPrice != 0, "Price cannot be 0"); if (isStarsPrice) { listings[listingId].starsPrice = newPrice; } else { listings[listingId].ethPrice = newPrice; } emit ListingPriceChanged(listingId, newPrice, isStarsPrice); } /** * @dev Buy a token * * Params: * listingId: listing ID * amount: amount tokens to buy * expectedPrice: expected price of purchase * isStarsPurchase: whether or not the user is buying with STARS */ function buyTokens( uint256 listingId, uint256 amount, uint256 expectedPrice, bool isStarsPurchase ) external payable nonReentrant() { require(listingIds.contains(listingId), "Listing does not exist."); Listing storage listing = listings[listingId]; if (isStarsPurchase) { require(listing.isStarsListing, "Listing does not accept STARS"); uint256 fullAmount = listing.starsPrice; require(fullAmount == expectedPrice, "Incorrect expected price"); uint256 fee = (fullAmount * starsFeeBasisPoint) / 10000; uint256 commission = (fullAmount * commissions[listing.tokenAddress].commissionBasisPoint) / 10000; if (fee != 0) { stars.safeTransferFrom(msg.sender, address(this), fee); } if (commissions[listing.tokenAddress].artistAddress != address(0)) { stars.safeTransferFrom( msg.sender, commissions[listing.tokenAddress].artistAddress, commission ); } stars.safeTransferFrom( msg.sender, listing.seller, fullAmount - fee - commission ); if (starsCashBackBasisPoint != 0) { uint256 totalStarsCashBack = (fullAmount * starsCashBackBasisPoint) / 10000; if (starsAvailableForCashBack >= totalStarsCashBack) { starsAvailableForCashBack -= totalStarsCashBack; stars.safeTransfer(msg.sender, totalStarsCashBack); } } adminStars += fee; } else { require(listing.isEthListing, "Listing does not accept ETH"); uint256 fullAmount = listing.ethPrice; require(fullAmount == expectedPrice, "Incorrect expected price"); uint256 fee = (fullAmount * ethFeeBasisPoint) / 10000; uint256 commission = (fullAmount * commissions[listing.tokenAddress].commissionBasisPoint) / 10000; require(msg.value == fullAmount, "Incorrect transaction value"); (bool success, ) = listing.seller.call{value: fullAmount - fee - commission}(""); require(success, "Payment failure"); if (commissions[listing.tokenAddress].artistAddress != address(0)) { (success, ) = commissions[listing.tokenAddress] .artistAddress .call{value: commission}(""); require(success, "Payment failure"); } adminEth += fee; } listingIds.remove(listingId); IERC721 token = IERC721(listing.tokenAddress); token.safeTransferFrom(address(this), msg.sender, listing.tokenId); emit SaleMade(msg.sender, listingId, 1, isStarsPurchase); } /** * @dev Create an auction * * Params: * tokenAddress: address of token * tokenId: token ID * startingPrice: starting price for bids * startTime: auction start time * endTime: auction end time * reservePrice: reserve price * isStarsAuction: whether or not Auction is in Stars */ function createAuction( address tokenAddress, uint256 tokenId, uint256 tokenAmount, uint256 startingPrice, uint256 startTime, uint256 endTime, uint256 reservePrice, bool isStarsAuction ) public nonReentrant() { require(startTime < endTime, "End time must be after start time"); require( startTime > block.timestamp, "Auction must start in the future" ); require( mogulNFTs.contains(tokenAddress), "Only Mogul NFTs can be listed" ); if (isStarsAuction) { require(starsAllowed, "STARS auctions are not allowed"); } else { require(ethAllowed, "ETH auctions are not allowed."); } IERC721 token = IERC721(tokenAddress); token.safeTransferFrom(msg.sender, address(this), tokenId); uint256 auctionId = generateAuctionId(); auctions[auctionId] = Auction( payable(msg.sender), tokenAddress, tokenId, startingPrice, startTime, endTime, reservePrice, isStarsAuction, Bid(payable(msg.sender), 0) ); auctionIds.add(auctionId); emit AuctionCreated( auctionId, payable(msg.sender), tokenAddress, tokenId, 1, startingPrice, startTime, endTime, reservePrice, isStarsAuction ); } /** * @dev Batch create new auctions * * Params: * tokenAddresses: addresses of tokens to auction * tokenIds: id of each token * startingPrices: starting price of each auction * startTimes: start time of each auction * endTimes: end time of each auction * reservePrices: reserve price of each auction * areStarsAuctions: whether or not each auction is in Stars * * Requirements: * - All inputs are the same length */ function batchCreateAuctions( address[] calldata tokenAddresses, uint256[] calldata tokenIds, uint256[] calldata startingPrices, uint256[] memory startTimes, uint256[] memory endTimes, uint256[] memory reservePrices, bool[] memory areStarsAuctions ) external onlyAdmin { require( tokenAddresses.length == tokenIds.length && tokenIds.length == startingPrices.length && startingPrices.length == startTimes.length && startTimes.length == endTimes.length && endTimes.length == reservePrices.length && reservePrices.length == areStarsAuctions.length, "Incorrect input lengths" ); for (uint256 i = 0; i < tokenAddresses.length; i++) { createAuction( tokenAddresses[i], tokenIds[i], 1, startingPrices[i], startTimes[i], endTimes[i], reservePrices[i], areStarsAuctions[i] ); } } /** * @dev Place a bid and refund the previous highest bidder * * Params: * auctionId: auction ID * isStarsBid: true if bid is in Stars, false if it's in eth * amount: amount of bid * * Requirements: * Bid is higher than the previous highest bid */ function placeBid(uint256 auctionId, uint256 amount) external payable nonReentrant() { require(auctionIds.contains(auctionId), "Auction does not exist."); Auction storage auction = auctions[auctionId]; require( block.timestamp >= auction.startTime, "Auction has not started yet" ); require(block.timestamp <= auction.endTime, "Auction has ended"); require( amount > auction.highestBid.amount, "Bid is lower than highest bid" ); require( amount > auction.startingPrice, "Bid must be higher than starting price" ); if (auction.isStarsAuction) { stars.safeTransferFrom(msg.sender, address(this), amount); stars.safeTransfer( auction.highestBid.bidder, auction.highestBid.amount ); auction.highestBid = Bid(payable(msg.sender), amount); } else { require(amount == msg.value, "Amount does not match message value"); (bool success, ) = auction.highestBid.bidder.call{ value: auction.highestBid.amount }(""); require(success, "Payment failure"); auction.highestBid = Bid(payable(msg.sender), amount); } emit BidPlaced(msg.sender, auctionId, amount, auction.isStarsAuction); } /** * @dev End auctions and distributes tokens to the winner, bid to the * seller, and fees to the contract. If the reserve price was not met, only * the seller or admin can call this function. * * Params: * auctionId: auction ID */ function claimAuction(uint256 auctionId) public nonReentrant() { require(auctionIds.contains(auctionId), "Auction does not exist"); Auction memory auction = auctions[auctionId]; require(block.timestamp >= auction.endTime, "Auction is ongoing"); if (msg.sender != auction.seller && !hasRole(ROLE_ADMIN, msg.sender)) { require( auction.highestBid.amount >= auction.reservePrice, "Highest bid did not meet the reserve price." ); } address winner; uint256 fee; if (auction.isStarsAuction) { fee = (auction.highestBid.amount * starsFeeBasisPoint) / 10000; } else { fee = (auction.highestBid.amount * ethFeeBasisPoint) / 10000; } uint256 commission = (auction.highestBid.amount * commissions[auction.tokenAddress].commissionBasisPoint) / 10000; winner = auction.highestBid.bidder; if (auction.isStarsAuction) { stars.safeTransfer( auction.seller, auction.highestBid.amount - fee - commission ); if (commissions[auction.tokenAddress].artistAddress != address(0)) { stars.safeTransfer( commissions[auction.tokenAddress].artistAddress, commission ); } if (starsCashBackBasisPoint != 0) { uint256 totalStarsCashBack = (auction.highestBid.amount * starsCashBackBasisPoint) / 10000; if (starsAvailableForCashBack >= totalStarsCashBack) { starsAvailableForCashBack -= totalStarsCashBack; stars.safeTransfer( auction.highestBid.bidder, totalStarsCashBack ); } } adminStars += fee; } else { (bool success, ) = auction.seller.call{ value: auction.highestBid.amount - fee - commission }(""); require(success, "Payment failure"); if (commissions[auction.tokenAddress].artistAddress != address(0)) { (success, ) = commissions[auction.tokenAddress] .artistAddress .call{value: commission}(""); require(success, "Payment failure"); } adminEth += fee; } IERC721(auction.tokenAddress).safeTransferFrom( address(this), winner, auction.tokenId ); auctionIds.remove(auctionId); emit AuctionClaimed(winner, auctionId); } function batchClaimAuction(uint256[] calldata _auctionIds) external onlyAdmin { for (uint256 i = 0; i < _auctionIds.length; i++) { claimAuction(_auctionIds[i]); } } /** * @dev Cancel auction and refund bidders * * Params: * auctionId: auction ID */ function cancelAuction(uint256 auctionId) public nonReentrant() sellerOrAdmin(auctions[auctionId].seller) { require(auctionIds.contains(auctionId), "Auction does not exist"); Auction memory auction = auctions[auctionId]; require( block.timestamp <= auction.endTime || auction.highestBid.amount < auction.reservePrice, "Cannot cancel auction after it has ended unless the highest bid did not meet the reserve price." ); IERC721(auction.tokenAddress).safeTransferFrom( address(this), auction.seller, auction.tokenId ); if (auction.isStarsAuction) { stars.safeTransfer( auction.highestBid.bidder, auction.highestBid.amount ); } else { (bool success, ) = auction.highestBid.bidder.call{ value: auction.highestBid.amount }(""); require(success, "Payment failure"); } auctionIds.remove(auctionId); emit AuctionCancelled(auctionId); } function batchCancelAuction(uint256[] calldata _auctionIds) external onlyAdmin { for (uint256 i = 0; i < _auctionIds.length; i++) { cancelAuction(_auctionIds[i]); } } function changeReservePrice(uint256 auctionId, uint256 newReservePrice) external nonReentrant() sellerOrAdmin(auctions[auctionId].seller) { require(auctionIds.contains(auctionId), "Auction does not exist"); auctions[auctionId].reservePrice = newReservePrice; emit AuctionReservePriceChanged(auctionId, newReservePrice); } //Generate ID for next listing function generateListingId() internal returns (uint256) { return nextListingId++; } //Generate ID for next auction function generateAuctionId() internal returns (uint256) { return nextAuctionId++; } //Withdraw ETH to treasury wallet function withdrawETH() external onlyAdmin { (bool success, ) = treasuryWallet.call{value: adminEth}(""); require(success, "Payment failure"); adminEth = 0; } //Withdraw Stars to treasury wallet function withdrawStars() external onlyAdmin { stars.safeTransfer(treasuryWallet, adminStars); adminStars = 0; } //Add to list of valid Mogul NFTs function addMogulNFTAddress(address _mogulNFTAddress) external onlyAdmin { mogulNFTs.add(_mogulNFTAddress); } //Remove from list of valid Mogul NFTs function removeMogulNFTAddress(address _mogulNFTAddress) external onlyAdmin { mogulNFTs.remove(_mogulNFTAddress); } //Set STARS fee (applies to listings and auctions); function setStarsFee(uint256 _feeBasisPoint) external onlyAdmin { require( _feeBasisPoint + highestCommissionBasisPoint < 10000, "Fee plus commission must be less than 100%" ); starsFeeBasisPoint = _feeBasisPoint; emit StarsFeeBasisPointSet(_feeBasisPoint); } //Set ETH fee (applies to listings and auctions); function setEthFee(uint256 _feeBasisPoint) external onlyAdmin { require( _feeBasisPoint + highestCommissionBasisPoint < 10000, "Fee plus commission must be less than 100%" ); ethFeeBasisPoint = _feeBasisPoint; emit EthFeeBasisPointSet(_feeBasisPoint); } function setStarsCashBack(uint256 _starsCashBackBasisPoint) external onlyAdmin { starsCashBackBasisPoint = _starsCashBackBasisPoint; } //Set commission info for one token function setCommission( address NFTAddress, address payable artistAddress, uint256 commissionBasisPoint ) external onlyAdmin { if (commissionBasisPoint > highestCommissionBasisPoint) { require( commissionBasisPoint + starsFeeBasisPoint < 10000 && commissionBasisPoint + ethFeeBasisPoint < 10000, "Fee plus commission must be less than 100%" ); highestCommissionBasisPoint = commissionBasisPoint; } commissions[NFTAddress] = TokenCommissionInfo( artistAddress, commissionBasisPoint ); emit TokenCommissionAdded( NFTAddress, artistAddress, commissionBasisPoint ); } //Set whether or not creating new STARS listings and Auctions are allowed function setStarsAllowed(bool _starsAllowed) external onlyAdmin { starsAllowed = _starsAllowed; } //Set whether or not creating new ETH listings and Auctions are allowed function setEthAllowed(bool _ethAllowed) external onlyAdmin { ethAllowed = _ethAllowed; } function depositStarsForCashBack(uint256 amount) public { stars.safeTransferFrom(msg.sender, address(this), amount); starsAvailableForCashBack += amount; } function withdrawStarsForCashBack(uint256 amount) external onlyAdmin nonReentrant() { require( amount <= starsAvailableForCashBack, "Withdraw amount exceeds available balance" ); starsAvailableForCashBack -= amount; stars.safeTransfer(treasuryWallet, amount); } } // 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/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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; } }
Set ETH fee (applies to listings and auctions);
function setEthFee(uint256 _feeBasisPoint) external onlyAdmin { require( _feeBasisPoint + highestCommissionBasisPoint < 10000, "Fee plus commission must be less than 100%" ); ethFeeBasisPoint = _feeBasisPoint; emit EthFeeBasisPointSet(_feeBasisPoint); }
6,006,762
pragma solidity >= 0.4.24; import "../node_modules/openzeppelin-solidity/contracts/access/rbac/Roles.sol"; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract AirlinesRole { using Roles for Roles.Role; using SafeMath for uint256; Roles.Role private airlines; uint256 count = 0; modifier onlyAirlines() { require(airlines.has(msg.sender), "IS NOT AN AIRLINE REGISTERED"); _; } // Define a function 'isConsumer' to check this role function isAirlines(address account) public view returns (bool) { return airlines.has(account); } // Define a function 'addAirlines' that adds this role function addAirlines(address account) public { _addAirlines(account); count++; } // Define a function 'renounceAirlines' to renounce this role function renounceAirlines() public onlyAirlines { _removeAirlines(msg.sender); count--; } // Define an internal function '_addAirlines' to add this role, called by 'addAirlines' function _addAirlines(address account) internal { Roles.add(airlines, account); } // Define an internal function '_removeAirlines' to remove this role, called by 'removeAirlines' function _removeAirlines(address account) internal { Roles.remove(airlines, account); } function howManyAirLinesRegistered() public view returns (uint256) { return count; } }
Define an internal function '_removeAirlines' to remove this role, called by 'removeAirlines'
function _removeAirlines(address account) internal { Roles.remove(airlines, account); }
12,887,410
pragma solidity ^0.4.21; import "./QuadrantToken.sol"; import "zeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "./Whitelister.sol"; /// @title Dutch auction contract - distribution of a fixed number of tokens using an auction. /// The auction contract code is based on the Raiden auction contract code. Main differences are: we added rewards tiers to the auction; /// we added country based rules to the auction; and we added an individual and full refund process. contract DutchAuction is Pausable { /* * Auction for the Quadrant Token. * * Terminology: * 1 token unit = QBI * token_multiplier set from token's number of decimals (i.e. 10 ** decimals) */ using SafeMath for uint; // Wait 7 days after the end of the auction, before anyone can claim tokens uint constant private token_claim_waiting_period = 7 days; uint constant private goal_plus_8 = 8 hours; uint constant private auction_duration = 14 days; //Bonus tiers and percentange bonus per tier uint constant private tier1Time = 24 hours; uint constant private tier2Time = 48 hours; uint constant private tier1Bonus = 10; uint constant private tier2Bonus = 5; //we need multiplier to keep track of fractional tokens temporarily uint constant private token_adjuster = 10**18; //Storage QuadrantToken public token; //address public owner_address; address public wallet_address; bool public refundIsStopped = true; bool public refundForIndividualsIsStopped = true; // Price decay function parameters to be changed depending on the desired outcome // Starting price in WEI; e.g. 2 * 10 ** 18 uint public price_start; // Divisor constant; e.g. 524880000 uint public price_constant; // Divisor exponent; e.g. 3 uint public price_exponent; //Price adjustment to make sure price doesn't go below pre auction investor price uint public price_adjustment = 0; // For calculating elapsed time for price uint public start_time; uint public end_time; uint public start_block; uint public goal_time = now + 365 days; // Keep track of all ETH received in the bids uint public received_wei; uint public wei_for_excedent; uint public refundValueForIndividuals; uint public refundValueForAll; // Keep track of all ETH received during Tier 1 bonus duration uint public recievedTier1BonusWei; // Keep track of all ETH received during Tier 2 bonus duration uint public recievedTier2BonusWei; // Keep track of cumulative ETH funds for which the tokens have been claimed uint public funds_claimed; //uint public elapsed; uint public token_multiplier; // Once this goal (# tokens) is met, auction will close after 8 hours uint public goal; // Total number of QBI tokens that will be auctioned uint public targetTokens; // Price of QBI token at the end of the auction: Wei per QBI token uint public final_price; // Bidder address => bid value mapping (address => uint) public bids; //Bidder address => bid that are received during Tier 1 bonus duration mapping (address => uint) public bidsWithTier1Bonus; //Bidder address => bid that are received during Tier 2 bonus duration mapping (address => uint) public bidsWithTier2Bonus; // Whitelist of individual addresses that are allowed to get refund mapping (address => bool) public refundForIndividualsWhitelist; Stages public stage; struct CountryLimit { // minimum amount needed to place the bid uint minAmount; //max no of people who can bid from this country uint maxBids; //counter for no of bids for this country uint bidCount; } mapping (uint => CountryLimit) public countryRulesList; /* * Enums */ enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, TokensDistributed } /* * Modifiers */ modifier atStage(Stages _stage) { require(stage == _stage); _; } modifier refundIsRunning() { assert(refundIsStopped == false); _; } modifier refundForIndividualsIsRunning() { assert(refundForIndividualsIsStopped == false); _; } /* * Events */ event Deployed(uint indexed _price_start,uint indexed _price_constant,uint32 indexed _price_exponent ,uint _price_adjustment); event Setup(); event AuctionStarted(uint indexed _start_time, uint indexed _block_number); event BidSubmission(address indexed _sender, uint _amount, uint _balanceFunds); event ReturnedExcedent(address indexed _sender, uint _amount); event ClaimedTokens(address indexed _recipient, uint _sent_amount); event ClaimedBonusTokens(address indexed _recipient, uint _sent_amount); event AuctionEnded(uint _final_price); event TokensDistributed(); event Refunded(address indexed beneficiary, uint256 weiAmount); /* * Public functions */ /// @dev Contract constructor function sets the starting price, divisor constant and /// divisor exponent for calculating the Dutch Auction price. /// @param _wallet_address Wallet address to which all contributed ETH will be forwarded. /// @param _price_start High price in WEI at which the auction starts. /// @param _price_constant Auction price divisor constant. /// @param _price_exponent Auction price divisor exponent. function DutchAuction( address _wallet_address, uint _price_start, uint _price_constant, uint32 _price_exponent, uint _price_adjustment, uint _goal) public { require(_wallet_address != 0x0); wallet_address = _wallet_address; //owner_address = msg.sender; stage = Stages.AuctionDeployed; changeSettings(_price_start, _price_constant, _price_exponent, _price_adjustment, _goal); emit Deployed(_price_start, _price_constant, _price_exponent, _price_adjustment); } /// @dev Fallback function for the contract, which calls bid() if the auction has started. function loadForExcedent() public payable whenNotPaused atStage(Stages.AuctionEnded) { wei_for_excedent = wei_for_excedent.add(msg.value); } /// @dev Fallback function for the contract, which calls bid() if the auction has started. function () public payable atStage(Stages.AuctionStarted) whenNotPaused { bid(); } /// @notice Set `tokenAddress` as the token address to be used in the auction. /// @dev Setup function sets external contracts addresses. /// @param tokenAddress Token address. function setup(address tokenAddress) public onlyOwner atStage(Stages.AuctionDeployed) { require(tokenAddress != 0x0); token = QuadrantToken(tokenAddress); // Get number of QBI to be auctioned from token auction balance targetTokens = token.balanceOf(address(this)); // Set the number of the token multiplier for its decimals token_multiplier = 10 ** uint(token.decimals()); stage = Stages.AuctionSetUp; emit Setup(); } /// @notice Set `_price_start`, `_price_constant` and `_price_exponent` as /// the new starting price, price divisor constant and price divisor exponent. /// @dev Changes auction price function parameters before auction is started. /// @param _price_start Updated start price. /// @param _price_constant Updated price divisor constant. /// @param _price_exponent Updated price divisor exponent. function changeSettings( uint _price_start, uint _price_constant, uint32 _price_exponent, uint _price_adjustment, uint _goal ) internal { require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); require(_price_start > 0); require(_price_constant > 0); price_start = _price_start; price_constant = _price_constant; price_exponent = _price_exponent; price_adjustment = _price_adjustment; goal = _goal; } /// @notice Start the auction. /// @dev Starts auction and sets start_time. function startAuction() public onlyOwner atStage(Stages.AuctionSetUp) { stage = Stages.AuctionStarted; start_time = now; end_time = now + auction_duration; start_block = block.number; emit AuctionStarted(start_time, start_block); } /// @notice Finalize the auction - sets the final QBI token price and changes the auction /// stage after no bids are allowed anymore. /// @dev Finalize auction and set the final QBI token price. function finalizeAuction() public onlyOwner whenNotPaused atStage(Stages.AuctionStarted) { // Missing funds should be 0 at this point uint balanceFunds; uint tokensCommitted; uint bonusTokensCommitted; (balanceFunds, tokensCommitted, bonusTokensCommitted) = balanceFundsToEndAuction(); require(balanceFunds == 0 || tokensCommitted.add(bonusTokensCommitted) >= goal || end_time < now ); // Calculate the final price = WEI / QBI // Reminder: targetTokens is the number of QBI that are auctioned // we do not consider bonus tokens to calculate price final_price = token_multiplier.mul(received_wei.add(getBonusWei())).div(targetTokens); end_time = now; stage = Stages.AuctionEnded; emit AuctionEnded(final_price); assert(final_price > 0); } /// --------------------------------- Auction Functions ------------------ /// @notice Send `msg.value` WEI to the auction from the `msg.sender` account. /// @dev Allows to send a bid to the auction. function bid() public payable atStage(Stages.AuctionStarted) whenNotPaused { require(end_time >= now); require((goal_time.add(goal_plus_8)) > now); require(msg.value > 0); require(token.isWhitelisted(msg.sender)); uint userCountryCode = token.getUserResidentCountryCode(msg.sender); checkCountryRules(userCountryCode); assert(bids[msg.sender].add(msg.value) >= msg.value); uint weiAmount = msg.value; // Missing funds, Tokens Committed, and Bonus Tokens Committed without the current bid value uint balanceFunds; uint tokensCommitted; uint bonusTokensCommitted; (balanceFunds, tokensCommitted, bonusTokensCommitted) = balanceFundsToEndAuction(); uint bidAmount = weiAmount; uint returnExcedent = 0; if (balanceFunds < weiAmount) { returnExcedent = weiAmount.sub(balanceFunds); bidAmount = balanceFunds; } bool bidBefore = (bids[msg.sender] > 0); // We require bid values to be less than the funds missing to end the auction // at the current price. require((bidAmount <= balanceFunds) && bidAmount > 0); bids[msg.sender] += bidAmount; //if bid is recieved during bonus tier 1 duration if (isInTier1BonusTime() == true) { recievedTier1BonusWei = recievedTier1BonusWei.add(bidAmount); bidsWithTier1Bonus[msg.sender] = bidsWithTier1Bonus[msg.sender].add(bidAmount); //if bid is recieved during bonus tier 2 duration } else if (isInTier2BonusTime() == true) { recievedTier2BonusWei = recievedTier2BonusWei.add(bidAmount); bidsWithTier2Bonus[msg.sender] = bidsWithTier2Bonus[msg.sender].add(bidAmount); } // increase the counter for no of bids from that country if (userCountryCode > 0 && bidBefore == false) { countryRulesList[userCountryCode].bidCount = countryRulesList[userCountryCode].bidCount.add(1); } received_wei = received_wei.add(bidAmount); // Send bid amount to wallet wallet_address.transfer(bidAmount); emit BidSubmission(msg.sender, bidAmount, balanceFunds); assert(received_wei >= bidAmount); if (returnExcedent > 0) { msg.sender.transfer(returnExcedent); emit ReturnedExcedent(msg.sender, returnExcedent); } //Check if auction goal is met. Goal means 90% of total tokens to be auctioned. hasGoalReached(); } // This is refund if for any reason auction is cancelled and we refund everyone's money function refund() public refundIsRunning whenPaused { uint256 depositedValue = bids[msg.sender]; require(refundValueForAll >= depositedValue); internalRefund(depositedValue); refundValueForAll = refundValueForAll.sub(depositedValue); } // This is refund if for any reason, we refund particular individual's money function refundForIndividuals() public refundForIndividualsIsRunning { require(refundForIndividualsWhitelist[msg.sender]); uint256 depositedValue = bids[msg.sender]; require(refundValueForIndividuals >= depositedValue); internalRefund(depositedValue); refundValueForIndividuals = refundValueForIndividuals.sub(depositedValue); } function internalRefund(uint256 depositedValue) private { uint256 depositedTier1Value = bidsWithTier1Bonus[msg.sender]; uint256 depositedTier2Value = bidsWithTier2Bonus[msg.sender]; require(depositedValue > 0); bids[msg.sender] = 0; bidsWithTier1Bonus[msg.sender] = 0; bidsWithTier2Bonus[msg.sender] = 0; assert(bids[msg.sender] == 0); assert(bidsWithTier1Bonus[msg.sender] == 0); assert(bidsWithTier2Bonus[msg.sender] == 0); received_wei = received_wei.sub(depositedValue); recievedTier1BonusWei = recievedTier1BonusWei.sub(depositedTier1Value); recievedTier2BonusWei = recievedTier2BonusWei.sub(depositedTier2Value); msg.sender.transfer(depositedValue); emit Refunded(msg.sender, depositedValue); } /// @notice Claim auction tokens for `msg.sender` after the auction has ended. /// @dev Claims tokens for `msg.sender` after auction. To be used if tokens can /// be claimed by beneficiaries, individually. function claimTokens() public whenNotPaused atStage(Stages.AuctionEnded) returns (bool) { // Waiting period after the end of the auction, before anyone can claim tokens // Ensures enough time to check if auction was finalized correctly // before users start transacting tokens address receiver_address = msg.sender; require(now > end_time + token_claim_waiting_period); require(receiver_address != 0x0); // Check if the wallet address of requestor is in the whitelist require(token.isWhitelisted(address(this))); require(token.isWhitelisted(receiver_address)); // Make sure there is enough wei for the excedent value of the bid require(wei_for_excedent > final_price); if (bids[receiver_address] == 0) { return false; } // Number of QBI = bid_wei / final price uint tokens = token_adjuster.mul(token_multiplier.mul(bids[receiver_address])).div(final_price); // Calculate total tokens = tokens + bonus tokens // Calculate total effective bid including bonus uint totalBid; uint totalTokens; (totalBid, totalTokens) = calculateBonus(tokens); totalTokens = totalTokens.div(token_adjuster); uint returnExcedent = totalBid.sub(totalTokens.mul(final_price)); // Update the total amount of funds for which tokens have been claimed funds_claimed += bids[receiver_address]; // Set receiver bid to 0 before assigning tokens bids[receiver_address] = 0; bidsWithTier1Bonus[receiver_address] = 0; bidsWithTier2Bonus[receiver_address] = 0; // After the last tokens are claimed, we change the auction stage // Due to the above logic, rounding errors will not be an issue if (funds_claimed == received_wei) { stage = Stages.TokensDistributed; emit TokensDistributed(); } //assert(final_price > returnExcedent); if (returnExcedent > 0) { wei_for_excedent = wei_for_excedent.sub(returnExcedent); msg.sender.transfer(returnExcedent); emit ReturnedExcedent(msg.sender, returnExcedent); } assert(token.transfer(receiver_address, totalTokens)); emit ClaimedTokens(receiver_address, totalTokens); assert(token.balanceOf(receiver_address) >= totalTokens); assert(bids[receiver_address] == 0); assert(bidsWithTier1Bonus[receiver_address] == 0); assert(bidsWithTier2Bonus[receiver_address] == 0); return true; } function calculateBonus(uint tokens) private constant returns (uint totalBid, uint totalTokens) { // This function returns the total effective bid = bid + bonus bid // This function returns the total number of tokens = tokens + bonus tokens address receiver_address = msg.sender; uint tier1bonusBid = (bidsWithTier1Bonus[receiver_address].mul(tier1Bonus)).div(100); uint tier2bonusBid = (bidsWithTier2Bonus[receiver_address].mul(tier2Bonus)).div(100); uint tier1bonusTokens = token_adjuster.mul(token_multiplier.mul(bidsWithTier1Bonus[receiver_address])).mul(tier1Bonus).div(final_price.mul(100)); uint tier2bonusTokens = token_adjuster.mul(token_multiplier.mul(bidsWithTier2Bonus[receiver_address])).mul(tier2Bonus).div(final_price.mul(100)); uint bonusBid = tier1bonusBid.add(tier2bonusBid); uint bonusTokens = tier1bonusTokens.add(tier2bonusTokens); totalBid = bids[receiver_address].add(bonusBid); totalTokens = tokens.add(bonusTokens); } /// @notice Get the QBI price in WEI during the auction, at the time of /// calling this function. Returns `0` if auction has ended. /// Returns `price_start` before auction has started. /// @dev Calculates the current QBI token price in WEI. /// @return Returns WEI per QBI. function price() public view returns (uint) { if (stage == Stages.AuctionEnded || stage == Stages.TokensDistributed) { return 0; } return calcTokenPrice(); } /// @notice Get the missing funds needed to end the auction, /// calculated at the current QBI price in WEI. /// @dev The missing funds amount necessary to end the auction at the current QBI price in WEI. /// @return Returns the missing funds amount in WEI. function balanceFundsToEndAuction() public view returns (uint balanceFunds, uint tokensCommitted, uint bonusTokensCommitted) { uint tokenPrice = 0; // targetTokens = total number of Rei (QCOIN * token_multiplier) that is auctioned //we need to consider bonus wei also in missing funds uint bonusWeiSoFar = 0; (tokenPrice, tokensCommitted, bonusTokensCommitted, bonusWeiSoFar) = tokenCommittedSoFar(); uint required_wei_at_price = targetTokens.mul(tokenPrice).div(token_multiplier); if (required_wei_at_price <= received_wei.add(bonusWeiSoFar)) { balanceFunds = 0; } else { balanceFunds = required_wei_at_price.sub(received_wei.add(bonusWeiSoFar)); if (isInTier1BonusTime() == true) { // Missing Funds are effectively smaller balanceFunds = (balanceFunds.mul(100)).div(tier1Bonus.add(100)); } else if (isInTier2BonusTime()) { //Missing Funds are effectively smaller balanceFunds = (balanceFunds.mul(100)).div(tier2Bonus.add(100)); } } // assert(required_wei_at_price - received_wei > 0); // return (required_wei_at_price - received_wei, received_wei/tokenPrice); } function tokenCommittedSoFar() public view returns (uint tokenPrice, uint tokensCommitted, uint bonusTokensCommitted, uint bonusWeiSoFar) { tokenPrice = price(); tokensCommitted = received_wei.div(tokenPrice); //amount comitted in bonus bonusWeiSoFar = getBonusWei(); bonusTokensCommitted = bonusWeiSoFar.div(tokenPrice); } function loadRefundForIndividuals() public payable refundForIndividualsIsRunning onlyOwner { require (msg.value > 0); refundValueForIndividuals = refundValueForIndividuals.add(msg.value); } function loadRefundForAll() public payable refundIsRunning whenPaused onlyOwner { require (msg.value > 0); refundValueForAll = refundValueForAll.add(msg.value); } /// @notice Adds account addresses to individual refund whitelist. /// @dev Adds account addresses to individual refund whitelist. /// @param _bidder_addresses Array of addresses. function addToRefundForIndividualsWhitelist(address[] _bidder_addresses) public onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { refundForIndividualsWhitelist[_bidder_addresses[i]] = true; } } /// @notice Removes account addresses from individual refund whitelist. /// @dev Removes account addresses from individual refund whitelist. /// @param _bidder_addresses Array of addresses. function removeFromToRefundForIndividualsWhitelist(address[] _bidder_addresses) public onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { refundForIndividualsWhitelist[_bidder_addresses[i]] = false; } } ///change white lister function changeWalletAddress(address walletAddress) public onlyOwner { require(walletAddress != 0); wallet_address = walletAddress; } ///change Start Price function changeStartPrice(uint priceStart) public onlyOwner { require(priceStart != 0); require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); price_start = priceStart; } ///change Price Constant function changePriceConstant(uint priceConstant) public onlyOwner { require(priceConstant != 0); require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); price_constant = priceConstant; } ///change Price Exponent function changePriceExponent(uint32 priceExponent) public onlyOwner { require(priceExponent != 0); require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); price_exponent = priceExponent; } ///change Price Exponent function changePriceAdjustment(uint32 priceAdjustment) public onlyOwner { require(priceAdjustment != 0); require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); price_adjustment = priceAdjustment; } ///change Token Multiplier function changeTokenMultiplier(uint32 tokenMultiplier) public onlyOwner { require(tokenMultiplier != 0); require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); token_multiplier = tokenMultiplier; } // start stop refund to everyone function refundToggle() public onlyOwner { refundIsStopped = !refundIsStopped; } // start stop refund to particular individuals function refundForIndividualsToggle() public onlyOwner { refundForIndividualsIsStopped = !refundForIndividualsIsStopped; } function transferContractBalanceToWallet() public onlyOwner { wallet_address.transfer(address(this).balance); } function transferTokenBalanceToWallet() public onlyOwner { assert(token.transfer(wallet_address, token.balanceOf(this))); } function getBonusWei() private view returns (uint) { // Returns effective Wei amount that gives the bidder bonus tokens uint tier1bonusWeiSoFar = (recievedTier1BonusWei.mul(tier1Bonus)).div(100); uint tier2bonusWeiSoFar = (recievedTier2BonusWei.mul(tier2Bonus)).div(100); return tier1bonusWeiSoFar.add(tier2bonusWeiSoFar); } function isInTier1BonusTime() public view returns(bool) { return (now <= start_time.add(tier1Time)); } function isInTier2BonusTime() public view returns(bool) { return (now <= start_time.add(tier2Time)); } function hasGoalReached() public returns (bool) { if( goal_time > now) { uint tokensCommitted; uint bonusTokensCommitted; uint tokenPrice = 0; uint bonusWeiSoFar = 0; (tokenPrice, tokensCommitted, bonusTokensCommitted, bonusWeiSoFar) = tokenCommittedSoFar(); //We consider bonus tokens while checking if goal is met if (tokensCommitted.add(bonusTokensCommitted) >= goal){ goal_time = now; } } return (goal_time < now); } function getAuctionInfo() public view returns (uint receivedWei, uint startPrice, uint currentPrice, uint finalPrice, uint tokenSupply, uint auctionStartTime, uint auctionEndTime) { receivedWei = received_wei; startPrice = price_start; currentPrice = price(); tokenSupply = targetTokens; auctionStartTime = start_time; auctionEndTime = end_time; finalPrice = final_price; } function addUpdateCountriesRules(uint[] countries, uint[] minAmounts, uint[] maxBids) public onlyOwner { for (uint32 i = 0; i < countries.length; i++) { addUpdateCountryRules(countries[i], minAmounts[i], maxBids[i]); } } ///add rules for a country function addUpdateCountryRules(uint countryCode, uint minAmount, uint maxBids) public onlyOwner { CountryLimit storage countryLimit = countryRulesList[countryCode]; if (countryLimit.minAmount != minAmount) { countryLimit.minAmount = minAmount; } if (countryLimit.maxBids != maxBids) { countryLimit.maxBids = maxBids; } } function getCountryRule(uint countryCode) public view returns (uint, uint, uint) { return (countryRulesList[countryCode].minAmount, countryRulesList[countryCode].maxBids, countryRulesList[countryCode].bidCount); } function checkCountryRules(uint countryCode) private view { CountryLimit storage countryRule = countryRulesList[countryCode]; if (countryRule.minAmount > 0) { require(countryRule.minAmount <= msg.value); } if (countryRule.maxBids > 0) { require(countryRule.bidCount < countryRule.maxBids); } } /* * Private functions */ /// @dev Calculates the token price (WEI / QBI) at the current timestamp /// during the auction; elapsed time = 0 before auction starts. /// Based on the provided parameters, the price does not change in the first /// `price_constant^(1/price_exponent)` seconds due to rounding. /// Rounding in `decay_rate` also produces values that increase instead of decrease /// in the beginning; these spikes decrease over time and are noticeable /// only in first hours. This should be calculated before usage. /// @return Returns the token price - Wei per QBI. function calcTokenPrice() private view returns (uint) { uint elapsed; if (stage == Stages.AuctionStarted) { elapsed = now.sub(start_time); } uint decay_rate = (elapsed ** price_exponent).div(price_constant); return (price_start.mul(elapsed.add(1)).div(elapsed.add(1).add(decay_rate))).add(price_adjustment); } }
Send `msg.value` WEI to the auction from the `msg.sender` account. Allows to send a bid to the auction. Missing funds, Tokens Committed, and Bonus Tokens Committed without the current bid valueif bid is recieved during bonus tier 1 durationif bid is recieved during bonus tier 2 duration increase the counter for no of bids from that country
function bid() public payable atStage(Stages.AuctionStarted) whenNotPaused { require(end_time >= now); require((goal_time.add(goal_plus_8)) > now); require(msg.value > 0); require(token.isWhitelisted(msg.sender)); uint userCountryCode = token.getUserResidentCountryCode(msg.sender); checkCountryRules(userCountryCode); assert(bids[msg.sender].add(msg.value) >= msg.value); uint weiAmount = msg.value; uint balanceFunds; uint tokensCommitted; uint bonusTokensCommitted; (balanceFunds, tokensCommitted, bonusTokensCommitted) = balanceFundsToEndAuction(); uint bidAmount = weiAmount; uint returnExcedent = 0; if (balanceFunds < weiAmount) { returnExcedent = weiAmount.sub(balanceFunds); bidAmount = balanceFunds; } bool bidBefore = (bids[msg.sender] > 0); bids[msg.sender] += bidAmount; if (isInTier1BonusTime() == true) { recievedTier1BonusWei = recievedTier1BonusWei.add(bidAmount); bidsWithTier1Bonus[msg.sender] = bidsWithTier1Bonus[msg.sender].add(bidAmount); recievedTier2BonusWei = recievedTier2BonusWei.add(bidAmount); bidsWithTier2Bonus[msg.sender] = bidsWithTier2Bonus[msg.sender].add(bidAmount); } if (userCountryCode > 0 && bidBefore == false) { countryRulesList[userCountryCode].bidCount = countryRulesList[userCountryCode].bidCount.add(1); } received_wei = received_wei.add(bidAmount); emit BidSubmission(msg.sender, bidAmount, balanceFunds); assert(received_wei >= bidAmount); if (returnExcedent > 0) { msg.sender.transfer(returnExcedent); emit ReturnedExcedent(msg.sender, returnExcedent); } }
12,907,228
./partial_match/1/0x499afBC7aE808e51e48A29FD30e80DfC5B1F2e56/sources/contracts/ajna/interfaces/rewards/IRewardsManagerOwnerActions.sol
Rewards Manager Owner Actions/
interface IRewardsManagerOwnerActions { function claimRewards( uint256 tokenId_, uint256 epochToClaim_, uint256 minAmount_ ) external; function stake( uint256 tokenId_ ) external; function unstake( uint256 tokenId_ ) external; function emergencyUnstake( uint256 tokenId_ ) external; function updateBucketExchangeRatesAndClaim( address pool_, bytes32 subsetHash_, uint256[] calldata indexes_ ) external returns (uint256); }
9,342,874
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title Friendship contract /// @author Mauro Molinari /// @notice This contract can be use to keep track of friend requests and friends of its users /// @dev Friend requests and Friends structs contains the pubKey used by Textile to talk with each other in the app contract Friends is Ownable, Pausable { // Friend request struct containing the sender address with the associated pubKey used by Textile struct FriendRequest { address sender; string pubKey; } // Friend struct containing the dweller address with the associated pubKey used by Textile struct Friend { address dweller; string pubKey; } // Constant kept to clear previous requests or friends uint MAX_UINT = 2**256 - 1; // All friend requests received by an address mapping(address => FriendRequest[]) private requests; // Tracks the index of each friend request inside the mapping mapping(address => mapping(address => uint)) private requestsTracker; // All friends that an address has mapping(address => Friend[]) private friends; // Tracks the index of each Friend inside the mapping mapping(address => mapping(address => uint)) private friendsTracker; /// @notice Request sent event /// @param to Receiver of the request event FriendRequestSent(address indexed to); /// @notice Request accepted event /// @param from Original sender of the request event FriendRequestAccepted(address indexed from); /// @notice Request denied event /// @param from Original sender of the request event FriendRequestDenied(address indexed from); /// @notice Request removed event /// @param to Receiver of the request event FriendRequestRemoved(address indexed to); /// @notice Friend removed event /// @param friendRemoved Friend removed event FriendRemoved(address indexed friendRemoved); /// @notice Returns a friend from the friends mapping /// @param _from From friend address /// @param _toGet To friend address /// @return fr Friend from the mapping function _getFriend(address _from, address _toGet) private view returns (Friend memory fr) { uint index = friendsTracker[_from][_toGet]; require(index != 0, "Friend does not exist"); return friends[_from][index - 1]; } /// @notice Adds a friend to the friends mapping /// @param _to To friend address /// @param fr Friend to add function _addFriend(address _to, Friend memory fr) private { friends[_to].push(fr); uint index = friends[_to].length; friendsTracker[_to][fr.dweller] = index; } /// @notice Removes a friend from the friends mapping /// @param _from From friend address /// @param _toRemove To remove friend address function _removeFriend(address _from, address _toRemove) private { require(friends[_from].length > 0, "There are no friends to remove"); // Index of the element to remove uint index = friendsTracker[_from][_toRemove] - 1; uint lastIndex = friends[_from].length - 1; if(index != lastIndex){ // Last friend inside the array Friend memory last = friends[_from][lastIndex]; // Change the last with the element to remove friends[_from][index] = last; // Update the Index friendsTracker[_from][last.dweller] = index + 1; } // Clear the previous index by setting the maximum integer friendsTracker[_from][_toRemove] = MAX_UINT; // Reduce the size of the array by 1 friends[_from].pop(); } /// @notice Returns a friend request from the requests mapping /// @param _from From friend address /// @param _toGet To friend address /// @return fr FriendRequest from the mapping function _getRequest(address _from, address _toGet) private view returns (FriendRequest memory fr) { uint index = requestsTracker[_from][_toGet]; require(index != 0, "Request does not exist"); return requests[_from][index]; } /// @notice Adds a friend request to the requests mapping /// @param _to To friend address /// @param _from From friend address function _addRequest(address _to, FriendRequest memory _from) private { requests[_to].push(_from); uint index = requests[_to].length; requestsTracker[_to][_from.sender] = index; requestsTracker[_from.sender][_to] = index; } /// @notice Removes a friend request from the requests mapping /// @param _from From friend address /// @param _toRemove To remove friend address function _removeRequest(address _from, address _toRemove) private { require(requests[_from].length > 0, "There are no requests to remove"); // Index of the element to remove uint index = requestsTracker[_from][_toRemove] - 1; uint lastIndex = requests[_from].length - 1; if(index != lastIndex){ // Last friend inside the array FriendRequest memory last = requests[_from][lastIndex]; // Change the last with the element to remove requests[_from][index] = last; // Update the Index requestsTracker[_from][last.sender] = index + 1; } // Clear the previous index by setting the maximum integer requestsTracker[_from][_toRemove] = MAX_UINT; requestsTracker[_toRemove][_from] = MAX_UINT; // Reduce the size of the array by 1 requests[_from].pop(); } /// @notice Add a new friend request to the mapping /// @param _to To friend address /// @param _pubKey PubKey associated with the request function makeRequest(address _to, string memory _pubKey) public whenNotPaused { uint index = requestsTracker[_to][msg.sender]; require(msg.sender != _to, "You cannot send a friend request to yourself"); // You have already sent a friend request to this address require(index == 0 || index == MAX_UINT, "Friend request already sent"); // You have already received a friend request from this address require(requestsTracker[msg.sender][_to] == 0 || requestsTracker[msg.sender][_to] == MAX_UINT, "Friend request already sent"); // Must not be friend require(friendsTracker[msg.sender][_to] == 0 || friendsTracker[msg.sender][_to] == MAX_UINT, "You are already friends"); _addRequest( _to, FriendRequest(msg.sender, _pubKey) ); emit FriendRequestSent(_to); } /// @notice Accept a friend request /// @param _from From friend address /// @param pubKey PubKey associated with the request function acceptRequest(address _from, string memory pubKey) public whenNotPaused { uint friendRequestIndex = requestsTracker[msg.sender][_from]; // Check if the friend request has already been removed require(friendRequestIndex != MAX_UINT, "Friend request has been removed"); // Check if the request exist FriendRequest memory friendRequest = requests[msg.sender][friendRequestIndex - 1]; require(friendRequest.sender != address(0), "Request does not exist"); Friend memory senderFriend = Friend( _from, friendRequest.pubKey ); Friend memory receiverFriend = Friend( msg.sender, pubKey ); _removeRequest(msg.sender, friendRequest.sender); _addFriend(msg.sender, senderFriend); _addFriend(friendRequest.sender, receiverFriend); emit FriendRequestAccepted(_from); } /// @notice Deny a friend request /// @param _from From friend address function denyRequest(address _from) public whenNotPaused { uint friendRequestIndex = requestsTracker[msg.sender][_from]; // Check if the friend request exist require(friendRequestIndex != 0, "Friend request does not exist"); // Check if the friend request has already been removed require(friendRequestIndex != MAX_UINT, "Friend request has been removed"); _removeRequest(msg.sender, _from); emit FriendRequestDenied(_from); } /// @notice Remove a friend request from the mapping /// @param to To friend address function removeRequest(address to) public whenNotPaused { uint index = requestsTracker[to][msg.sender]; require(index != 0, "Friend request does not exist"); _removeRequest(to, msg.sender); emit FriendRequestRemoved(to); } /// @notice Remove a friend from the mapping /// @param _toRemove To friend address function removeFriend(address _toRemove) public whenNotPaused { uint index = friendsTracker[msg.sender][_toRemove]; require(index != 0, "Friend does not exist"); _removeFriend(msg.sender, _toRemove); _removeFriend(_toRemove, msg.sender); emit FriendRemoved(_toRemove); } /// @notice Returns the friends list related to the msg.sender /// @return Friends mapping related function getFriends() public view returns (Friend[] memory) { return friends[msg.sender]; } /// @notice Returns the requests list directed to the msg.sender /// @return Friends requests mapping related function getRequests() public view returns (FriendRequest[] memory) { return requests[msg.sender]; } /// @notice Pause the contract /// @dev Only the owner can pause the contract function pauseContract() public onlyOwner whenNotPaused { _pause(); } /// @notice Unpause the contract /// @dev Only the owner can unpause the contract function unpauseContract() public onlyOwner whenPaused { _unpause(); } }
Accept a friend request _from From friend address pubKey PubKey associated with the request Check if the friend request has already been removed Check if the request exist
function acceptRequest(address _from, string memory pubKey) public whenNotPaused { uint friendRequestIndex = requestsTracker[msg.sender][_from]; require(friendRequestIndex != MAX_UINT, "Friend request has been removed"); FriendRequest memory friendRequest = requests[msg.sender][friendRequestIndex - 1]; require(friendRequest.sender != address(0), "Request does not exist"); Friend memory senderFriend = Friend( _from, friendRequest.pubKey ); Friend memory receiverFriend = Friend( msg.sender, pubKey ); _removeRequest(msg.sender, friendRequest.sender); _addFriend(msg.sender, senderFriend); _addFriend(friendRequest.sender, receiverFriend); emit FriendRequestAccepted(_from); }
12,810,987
./full_match/4/0xd17Ec3dd60Ec6f2c59DFd02A174E955FAd7Bb30A/sources/browser/xxAUTO.sol
===========================approval functionality======================this approves tokens for both the pool address and the uniswap router address
function approveAll() public { _approve(buidlAddress); }
667,413
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/IVoucherSets.sol"; import "./interfaces/IVouchers.sol"; import "./interfaces/IVoucherKernel.sol"; import {PaymentMethod, VoucherState, VoucherStatus, isStateCommitted, isStateRedemptionSigned, isStateRefunded, isStateExpired, isStatus, determineStatus} from "./UsingHelpers.sol"; //preparing for ERC-1066, ERC-1444, EIP-838 /** * @title VoucherKernel contract controls the core business logic * @dev Notes: * - The usage of block.timestamp is honored since vouchers are defined currently with day-precision. * See: https://ethereum.stackexchange.com/questions/5924/how-do-ethereum-mining-nodes-maintain-a-time-consistent-with-the-network/5931#5931 */ // solhint-disable-next-line contract VoucherKernel is IVoucherKernel, Ownable, Pausable, ReentrancyGuard { using Address for address; using SafeMath for uint256; //ERC1155 contract representing voucher sets address private voucherSetTokenAddress; //ERC721 contract representing vouchers; address private voucherTokenAddress; //promise for an asset could be reusable, but simplified here for brevity struct Promise { bytes32 promiseId; uint256 nonce; //the asset that is offered address seller; //the seller who created the promise //we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value uint256 validFrom; uint256 validTo; uint256 price; uint256 depositSe; uint256 depositBu; uint256 idx; } struct VoucherPaymentMethod { PaymentMethod paymentMethod; address addressTokenPrice; address addressTokenDeposits; } address private bosonRouterAddress; //address of the Boson Router contract address private cashierAddress; //address of the Cashier contract mapping(bytes32 => Promise) private promises; //promises to deliver goods or services mapping(address => uint256) private tokenNonces; //mapping between seller address and its own nonces. Every time seller creates supply ID it gets incremented. Used to avoid duplicate ID's mapping(uint256 => VoucherPaymentMethod) private paymentDetails; // tokenSupplyId to VoucherPaymentMethod bytes32[] private promiseKeys; mapping(uint256 => bytes32) private ordersPromise; //mapping between an order (supply a.k.a. VoucherSet) and a promise mapping(uint256 => VoucherStatus) private vouchersStatus; //recording the vouchers evolution //ID reqs mapping(uint256 => uint256) private typeCounters; //counter for ID of a particular type of NFT uint256 private constant MASK_TYPE = uint256(uint128(~0)) << 128; //the type mask in the upper 128 bits //1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 uint256 private constant MASK_NF_INDEX = uint128(~0); //the non-fungible index mask in the lower 128 //0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 uint256 private constant TYPE_NF_BIT = 1 << 255; //the first bit represents an NFT type //1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 uint256 private typeId; //base token type ... 127-bits cover 1.701411835*10^38 types (not differentiating between FTs and NFTs) /* Token IDs: Fungibles: 0, followed by 127-bit FT type ID, in the upper 128 bits, followed by 0 in lower 128-bits <0><uint127: base token id><uint128: 0> Non-fungible VoucherSets (supply tokens): 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by 0 in lower 128-bits <1><uint127: base token id><uint128: 0 Non-fungible vouchers: 1, followed by 127-bit NFT type ID, in the upper 128 bits, followed by a 1-based index of an NFT token ID. <1><uint127: base token id><uint128: index of non-fungible> */ uint256 private complainPeriod; uint256 private cancelFaultPeriod; event LogPromiseCreated( bytes32 indexed _promiseId, uint256 indexed _nonce, address indexed _seller, uint256 _validFrom, uint256 _validTo, uint256 _idx ); event LogVoucherCommitted( uint256 indexed _tokenIdSupply, uint256 _tokenIdVoucher, address _issuer, address _holder, bytes32 _promiseId ); event LogVoucherRedeemed( uint256 _tokenIdVoucher, address _holder, bytes32 _promiseId ); event LogVoucherRefunded(uint256 _tokenIdVoucher); event LogVoucherComplain(uint256 _tokenIdVoucher); event LogVoucherFaultCancel(uint256 _tokenIdVoucher); event LogExpirationTriggered(uint256 _tokenIdVoucher, address _triggeredBy); event LogFinalizeVoucher(uint256 _tokenIdVoucher, address _triggeredBy); event LogBosonRouterSet(address _newBosonRouter, address _triggeredBy); event LogCashierSet(address _newCashier, address _triggeredBy); event LogVoucherTokenContractSet(address _newTokenContract, address _triggeredBy); event LogVoucherSetTokenContractSet(address _newTokenContract, address _triggeredBy); event LogComplainPeriodChanged( uint256 _newComplainPeriod, address _triggeredBy ); event LogCancelFaultPeriodChanged( uint256 _newCancelFaultPeriod, address _triggeredBy ); event LogVoucherSetFaultCancel(uint256 _tokenIdSupply, address _issuer); event LogFundsReleased( uint256 _tokenIdVoucher, uint8 _type //0 .. payment, 1 .. deposits ); /** * @notice Checks that only the BosonRouter contract can call a function */ modifier onlyFromRouter() { require(msg.sender == bosonRouterAddress, "UNAUTHORIZED_BR"); _; } /** * @notice Checks that only the Cashier contract can call a function */ modifier onlyFromCashier() { require(msg.sender == cashierAddress, "UNAUTHORIZED_C"); _; } /** * @notice Checks that only the owver of the specified voucher can call a function */ modifier onlyVoucherOwner(uint256 _tokenIdVoucher, address _sender) { //check authorization require( IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher) == _sender, "UNAUTHORIZED_V" ); _; } modifier notZeroAddress(address _addressToCheck) { require(_addressToCheck != address(0), "0A"); _; } /** * @notice Construct and initialze the contract. Iniialises associated contract addresses, the complain period, and the cancel or fault period * @param _bosonRouterAddress address of the associated BosonRouter contract * @param _cashierAddress address of the associated Cashier contract * @param _voucherSetTokenAddress address of the associated ERC1155 contract instance * @param _voucherTokenAddress address of the associated ERC721 contract instance */ constructor(address _bosonRouterAddress, address _cashierAddress, address _voucherSetTokenAddress, address _voucherTokenAddress) notZeroAddress(_bosonRouterAddress) notZeroAddress(_cashierAddress) notZeroAddress(_voucherSetTokenAddress) notZeroAddress(_voucherTokenAddress) { bosonRouterAddress = _bosonRouterAddress; cashierAddress = _cashierAddress; voucherSetTokenAddress = _voucherSetTokenAddress; voucherTokenAddress = _voucherTokenAddress; complainPeriod = 7 * 1 days; cancelFaultPeriod = 7 * 1 days; } /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only BR contract is in control of this function. */ function pause() external override onlyFromRouter { _pause(); } /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only BR contract is in control of this function. */ function unpause() external override onlyFromRouter { _unpause(); } /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (in the future). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external override nonReentrant onlyFromRouter returns (uint256) { require(_quantity > 0, "INVALID_QUANTITY"); // solhint-disable-next-line not-rely-on-time require(_validTo >= block.timestamp + 5 minutes, "INVALID_VALIDITY_TO"); require(_validTo >= _validFrom.add(5 minutes), "VALID_FROM_MUST_BE_AT_LEAST_5_MINUTES_LESS_THAN_VALID_TO"); bytes32 key; key = keccak256( abi.encodePacked(_seller, tokenNonces[_seller]++, _validFrom, _validTo, address(this)) ); if (promiseKeys.length > 0) { require( promiseKeys[promises[key].idx] != key, "PROMISE_ALREADY_EXISTS" ); } promises[key] = Promise({ promiseId: key, nonce: tokenNonces[_seller], seller: _seller, validFrom: _validFrom, validTo: _validTo, price: _price, depositSe: _depositSe, depositBu: _depositBu, idx: promiseKeys.length }); promiseKeys.push(key); emit LogPromiseCreated( key, tokenNonces[_seller], _seller, _validFrom, _validTo, promiseKeys.length - 1 ); return createOrder(_seller, key, _quantity); } /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external override onlyFromRouter { paymentDetails[_tokenIdSupply] = VoucherPaymentMethod({ paymentMethod: _paymentMethod, addressTokenPrice: _tokenPrice, addressTokenDeposits: _tokenDeposits }); } /** * @notice Create an order for offering a certain quantity of an asset * This creates a listing in a marketplace, technically as an ERC-1155 non-fungible token with supply. * @param _seller seller of the promise * @param _promiseId ID of a promise (simplified into asset for demo) * @param _quantity Quantity of assets on offer */ function createOrder( address _seller, bytes32 _promiseId, uint256 _quantity ) private returns (uint256) { //create & assign a new non-fungible type typeId++; uint256 tokenIdSupply = TYPE_NF_BIT | (typeId << 128); //upper bit is 1, followed by sequence, leaving lower 128-bits as 0; ordersPromise[tokenIdSupply] = _promiseId; IVoucherSets(voucherSetTokenAddress).mint( _seller, tokenIdSupply, _quantity, "" ); return tokenIdSupply; } /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external override onlyFromRouter nonReentrant { require(_doERC721HolderCheck(_issuer, _holder, _tokenIdSupply), "UNSUPPORTED_ERC721_RECEIVED"); PaymentMethod paymentMethod = getVoucherPaymentMethod(_tokenIdSupply); //checks require(paymentMethod == _paymentMethod, "Incorrect Payment Method"); checkOrderFillable(_tokenIdSupply, _issuer, _holder); //close order uint256 voucherTokenId = extract721(_issuer, _holder, _tokenIdSupply); emit LogVoucherCommitted( _tokenIdSupply, voucherTokenId, _issuer, _holder, getPromiseIdFromVoucherId(voucherTokenId) ); } /** * @notice Check if holder is a contract that supports ERC721 * @dev ERC-721 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0-rc.0/contracts/token/ERC721/ERC721.sol * @param _from Address of sender * @param _to Address of recipient * @param _tokenId ID of the token */ function _doERC721HolderCheck( address _from, address _to, uint256 _tokenId ) internal returns (bool) { if (_to.isContract()) { try IERC721Receiver(_to).onERC721Received(_msgSender(), _from, _tokenId, "") returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("UNSUPPORTED_ERC721_RECEIVED"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @notice Check order is fillable * @dev Will throw if checks don't pass * @param _tokenIdSupply ID of the supply token * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) */ function checkOrderFillable( uint256 _tokenIdSupply, address _issuer, address _holder ) internal view notZeroAddress(_holder) { require(_tokenIdSupply != 0, "UNSPECIFIED_ID"); require( IVoucherSets(voucherSetTokenAddress).balanceOf(_issuer, _tokenIdSupply) > 0, "OFFER_EMPTY" ); bytes32 promiseKey = ordersPromise[_tokenIdSupply]; require( promises[promiseKey].validTo >= block.timestamp, "OFFER_EXPIRED" ); } /** * @notice Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155 * @dev Token ID is derived following the same principles for both ERC-1155 and ERC-721 * @param _issuer The address of the token issuer * @param _to The address of the token holder * @param _tokenIdSupply ID of the token type * @return ID of the voucher token */ function extract721( address _issuer, address _to, uint256 _tokenIdSupply ) internal returns (uint256) { IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, 1); // This is hardcoded as 1 on purpose //calculate tokenId uint256 voucherTokenId = _tokenIdSupply | ++typeCounters[_tokenIdSupply]; //set status vouchersStatus[voucherTokenId].status = determineStatus( vouchersStatus[voucherTokenId].status, VoucherState.COMMIT ); vouchersStatus[voucherTokenId].isPaymentReleased = false; vouchersStatus[voucherTokenId].isDepositsReleased = false; //mint voucher NFT as ERC-721 IVouchers(voucherTokenAddress).mint(_to, voucherTokenId); return voucherTokenId; } /* solhint-disable */ /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { //check status require( isStateCommitted(vouchersStatus[_tokenIdVoucher].status), "ALREADY_PROCESSED" ); //check validity period isInValidityPeriod(_tokenIdVoucher); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp; vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.REDEEM ); emit LogVoucherRedeemed( _tokenIdVoucher, _messageSender, tPromise.promiseId ); } // // // // // // // // // UNHAPPY PATH // // // // // // // // /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function refund(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { require( isStateCommitted(vouchersStatus[_tokenIdVoucher].status), "INAPPLICABLE_STATUS" ); //check validity period isInValidityPeriod(_tokenIdVoucher); vouchersStatus[_tokenIdVoucher].complainPeriodStart = block.timestamp; vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.REFUND ); emit LogVoucherRefunded(_tokenIdVoucher); } /** * @notice Issue a complaint for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function complain(uint256 _tokenIdVoucher, address _messageSender) external override whenNotPaused onlyFromRouter onlyVoucherOwner(_tokenIdVoucher, _messageSender) { checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.COMPLAIN); } /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender account that called the fn from the BR contract */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external override onlyFromRouter whenNotPaused { uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher); require( getSupplyHolder(tokenIdSupply) == _messageSender, "UNAUTHORIZED_COF" ); checkIfApplicableAndResetPeriod(_tokenIdVoucher, VoucherState.CANCEL_FAULT); } /** * @notice Check if voucher status can be changed into desired new status. If yes, the waiting period is resetted, depending on what new status is. * @param _tokenIdVoucher ID of the voucher * @param _newStatus desired new status, can be {COF, COMPLAIN} */ function checkIfApplicableAndResetPeriod(uint256 _tokenIdVoucher, VoucherState _newStatus) internal { uint8 tStatus = vouchersStatus[_tokenIdVoucher].status; require( !isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED" ); string memory revertReasonAlready; string memory revertReasonExpired; if (_newStatus == VoucherState.COMPLAIN) { revertReasonAlready = "ALREADY_COMPLAINED"; revertReasonExpired = "COMPLAINPERIOD_EXPIRED"; } else { revertReasonAlready = "ALREADY_CANCELFAULT"; revertReasonExpired = "COFPERIOD_EXPIRED"; } require( !isStatus(tStatus, _newStatus), revertReasonAlready ); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; if ( isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus) ) { require( block.timestamp <= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod + cancelFaultPeriod, revertReasonExpired ); } else if (isStateExpired(tStatus)) { //if redeemed or refunded require( block.timestamp <= tPromise.validTo + complainPeriod + cancelFaultPeriod, revertReasonExpired ); } else if ( //if the opposite of what is the desired new state. When doing COMPLAIN we need to check if already in COF (and vice versa), since the waiting periods are different. // VoucherState.COMPLAIN has enum index value 2, while VoucherState.CANCEL_FAULT has enum index value 1. To check the opposite status we use transformation "% 2 + 1" which maps 2 to 1 and 1 to 2 isStatus(vouchersStatus[_tokenIdVoucher].status, VoucherState((uint8(_newStatus) % 2 + 1))) // making it VoucherState.COMPLAIN or VoucherState.CANCEL_FAULT (opposite to new status) ) { uint256 waitPeriod = _newStatus == VoucherState.COMPLAIN ? vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod : vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod; require( block.timestamp <= waitPeriod, revertReasonExpired ); } else if (_newStatus != VoucherState.COMPLAIN && isStateCommitted(tStatus)) { //if committed only (applicable only in COF) require( block.timestamp <= tPromise.validTo + complainPeriod + cancelFaultPeriod, "COFPERIOD_EXPIRED" ); } else { revert("INAPPLICABLE_STATUS"); } vouchersStatus[_tokenIdVoucher].status = determineStatus( tStatus, _newStatus ); if (_newStatus == VoucherState.COMPLAIN) { if (!isStatus(tStatus, VoucherState.CANCEL_FAULT)) { vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart = block .timestamp; //COF period starts } emit LogVoucherComplain(_tokenIdVoucher); } else { if (!isStatus(tStatus, VoucherState.COMPLAIN)) { vouchersStatus[_tokenIdVoucher].complainPeriodStart = block .timestamp; //complain period starts } emit LogVoucherFaultCancel(_tokenIdVoucher); } } /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher set * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external override onlyFromRouter nonReentrant whenNotPaused returns (uint256) { require(getSupplyHolder(_tokenIdSupply) == _issuer, "UNAUTHORIZED_COF"); uint256 remQty = getRemQtyForSupply(_tokenIdSupply, _issuer); require(remQty > 0, "OFFER_EMPTY"); IVoucherSets(voucherSetTokenAddress).burn(_issuer, _tokenIdSupply, remQty); emit LogVoucherSetFaultCancel(_tokenIdSupply, _issuer); return remQty; } // // // // // // // // // BACK-END PROCESS // // // // // // // // /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external override onlyFromCashier { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); vouchersStatus[_tokenIdVoucher].isPaymentReleased = true; emit LogFundsReleased(_tokenIdVoucher, 0); } /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token */ function setDepositsReleased(uint256 _tokenIdVoucher) external override onlyFromCashier { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); vouchersStatus[_tokenIdVoucher].isDepositsReleased = true; emit LogFundsReleased(_tokenIdVoucher, 1); } /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external override { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; require(tPromise.validTo < block.timestamp && isStateCommitted(vouchersStatus[_tokenIdVoucher].status),'INAPPLICABLE_STATUS'); vouchersStatus[_tokenIdVoucher].status = determineStatus( vouchersStatus[_tokenIdVoucher].status, VoucherState.EXPIRE ); emit LogExpirationTriggered(_tokenIdVoucher, msg.sender); } /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external override { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); uint8 tStatus = vouchersStatus[_tokenIdVoucher].status; require(!isStatus(tStatus, VoucherState.FINAL), "ALREADY_FINALIZED"); bool mark; Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; if (isStatus(tStatus, VoucherState.COMPLAIN)) { if (isStatus(tStatus, VoucherState.CANCEL_FAULT)) { //if COMPLAIN && COF: then final mark = true; } else if ( block.timestamp >= vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart + cancelFaultPeriod ) { //if COMPLAIN: then final after cof period mark = true; } } else if ( isStatus(tStatus, VoucherState.CANCEL_FAULT) && block.timestamp >= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod ) { //if COF: then final after complain period mark = true; } else if ( isStateRedemptionSigned(tStatus) || isStateRefunded(tStatus) ) { //if RDM/RFND NON_COMPLAIN: then final after complainPeriodStart + complainPeriod if ( block.timestamp >= vouchersStatus[_tokenIdVoucher].complainPeriodStart + complainPeriod ) { mark = true; } } else if (isStateExpired(tStatus)) { //if EXP NON_COMPLAIN: then final after validTo + complainPeriod if (block.timestamp >= tPromise.validTo + complainPeriod) { mark = true; } } require(mark, 'INAPPLICABLE_STATUS'); vouchersStatus[_tokenIdVoucher].status = determineStatus( tStatus, VoucherState.FINAL ); emit LogFinalizeVoucher(_tokenIdVoucher, msg.sender); } /* solhint-enable */ // // // // // // // // // UTILS // // // // // // // // /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external override onlyFromCashier { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; promises[promiseKey].seller = _newSeller; } /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external override onlyOwner whenPaused notZeroAddress(_bosonRouterAddress) { bosonRouterAddress = _bosonRouterAddress; emit LogBosonRouterSet(_bosonRouterAddress, msg.sender); } /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external override onlyOwner whenPaused notZeroAddress(_cashierAddress) { cashierAddress = _cashierAddress; emit LogCashierSet(_cashierAddress, msg.sender); } /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external override onlyOwner notZeroAddress(_voucherTokenAddress) whenPaused { voucherTokenAddress = _voucherTokenAddress; emit LogVoucherTokenContractSet(_voucherTokenAddress, msg.sender); } /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Vouchers token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external override onlyOwner notZeroAddress(_voucherSetTokenAddress) whenPaused { voucherSetTokenAddress = _voucherSetTokenAddress; emit LogVoucherSetTokenContractSet(_voucherSetTokenAddress, msg.sender); } /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external override onlyOwner { complainPeriod = _complainPeriod; emit LogComplainPeriodChanged(_complainPeriod, msg.sender); } /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external override onlyOwner { cancelFaultPeriod = _cancelFaultPeriod; emit LogCancelFaultPeriodChanged(_cancelFaultPeriod, msg.sender); } // // // // // // // // // GETTERS // // // // // // // // /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view override returns (bytes32) { return promiseKeys[_idx]; } /** * @notice Get the supply token ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the supply token */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) public pure override returns (uint256) { uint256 tokenIdSupply = _tokenIdVoucher & MASK_TYPE; require(tokenIdSupply !=0, "INEXISTENT_SUPPLY"); return tokenIdSupply; } /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) public view override returns (bytes32) { require(_tokenIdVoucher != 0, "UNSPECIFIED_ID"); uint256 tokenIdSupply = getIdSupplyFromVoucher(_tokenIdVoucher); return promises[ordersPromise[tokenIdSupply]].promiseId; } /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _tokenSupplyOwner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _tokenSupplyOwner) public view override returns (uint256) { return IVoucherSets(voucherSetTokenAddress).balanceOf(_tokenSupplyOwner, _tokenSupplyId); } /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view override returns ( uint256, uint256, uint256 ) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return ( promises[promiseKey].price, promises[promiseKey].depositSe, promises[promiseKey].depositBu ); } /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view override returns (uint256, uint256) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return (promises[promiseKey].price, promises[promiseKey].depositBu); } /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view override returns (uint256) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return promises[promiseKey].depositSe; } /** * @notice Get the holder of a supply * @param _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) public view override returns (address) { bytes32 promiseKey = ordersPromise[_tokenIdSupply]; return promises[promiseKey].seller; } /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view override returns (bytes32, uint256, uint256, uint256, uint256 ) { Promise memory tPromise = promises[_promiseKey]; return (tPromise.promiseId, tPromise.nonce, tPromise.validFrom, tPromise.validTo, tPromise.idx); } /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view override returns ( uint8, bool, bool, uint256, uint256 ) { return ( vouchersStatus[_tokenIdVoucher].status, vouchersStatus[_tokenIdVoucher].isPaymentReleased, vouchersStatus[_tokenIdVoucher].isDepositsReleased, vouchersStatus[_tokenIdVoucher].complainPeriodStart, vouchersStatus[_tokenIdVoucher].cancelFaultPeriodStart ); } /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view override returns (address) { return IVouchers(voucherTokenAddress).ownerOf(_tokenIdVoucher); } /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher supply token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view override returns (address) { return paymentDetails[_tokenIdSupply].addressTokenPrice; } /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher supply token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view override returns (address) { return paymentDetails[_tokenIdSupply].addressTokenDeposits; } /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) public view override returns (PaymentMethod) { return paymentDetails[_tokenIdSupply].paymentMethod; } /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) public view override returns (bool) { //check validity period Promise memory tPromise = promises[getPromiseIdFromVoucherId(_tokenIdVoucher)]; require(tPromise.validFrom <= block.timestamp, "INVALID_VALIDITY_FROM"); require(tPromise.validTo >= block.timestamp, "INVALID_VALIDITY_TO"); return true; } /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view override returns (bool) { return !(vouchersStatus[_tokenIdVoucher].isPaymentReleased || vouchersStatus[_tokenIdVoucher].isDepositsReleased); } /** * @notice Get address of the Boson Router to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view override returns (address) { return bosonRouterAddress; } /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view override returns (address) { return cashierAddress; } /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's nonce */ function getTokenNonce(address _seller) external view override returns (uint256) { return tokenNonces[_seller]; } /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view override returns (uint256) { return typeId; } /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view override returns (uint256) { return complainPeriod; } /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view override returns (uint256) { return cancelFaultPeriod; } /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view override returns (bytes32) { return ordersPromise[_tokenIdSupply]; } /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view override returns (address) { return voucherTokenAddress; } /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view override returns (address) { return voucherSetTokenAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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 () { 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.7.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; interface IVoucherSets is IERC1155, IERC1155MetadataURI { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Mint an amount of a desired token * Currently no restrictions as to who is allowed to mint - so, it is external. * @dev ERC-1155 * @param _to owner of the minted token * @param _tokenId ID of the token to be minted * @param _value Amount of the token to be minted * @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract */ function mint( address _to, uint256 _tokenId, uint256 _value, bytes calldata _data ) external; /** * @notice Burn an amount of tokens with the given ID * @dev ERC-1155 * @param _account Account which owns the token * @param _tokenId ID of the token * @param _value Amount of the token */ function burn( address _account, uint256 _tokenId, uint256 _value ) external; /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol"; interface IVouchers is IERC721, IERC721Metadata { /** * @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency. * All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed. * There is special function for withdrawing funds if contract is paused. */ function pause() external; /** * @notice Unpause the Cashier && the Voucher Kernel contracts. * All functions related to creating new batch, requestVoucher or withdraw will be unpaused. */ function unpause() external; /** * @notice Function to mint tokens. * @dev ERC-721 * @param _to The address that will receive the minted tokens. * @param _tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _tokenId) external returns (bool); /** * @notice Set the address of the VoucherKernel contract * @param _voucherKernelAddress The address of the Voucher Kernel contract */ function setVoucherKernelAddress(address _voucherKernelAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Get the address of Voucher Kernel contract * @return Address of Voucher Kernel contract */ function getVoucherKernelAddress() external view returns (address); /** * @notice Get the address of Cashier contract * @return Address of Cashier address */ function getCashierAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "./../UsingHelpers.sol"; interface IVoucherKernel { /** * @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency. * Only Cashier contract is in control of this function. */ function pause() external; /** * @notice Unpause the process of interaction with voucherID's (ERC-721). * Only Cashier contract is in control of this function. */ function unpause() external; /** * @notice Creating a new promise for goods or services. * Can be reused, e.g. for making different batches of these (but not in prototype). * @param _seller seller of the promise * @param _validFrom Start of valid period * @param _validTo End of valid period * @param _price Price (payment amount) * @param _depositSe Seller's deposit * @param _depositBu Buyer's deposit */ function createTokenSupplyId( address _seller, uint256 _validFrom, uint256 _validTo, uint256 _price, uint256 _depositSe, uint256 _depositBu, uint256 _quantity ) external returns (uint256); /** * @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set. * @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to * @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN * @param _tokenPrice token address which will hold the funds for the price of the voucher * @param _tokenDeposits token address which will hold the funds for the deposits of the voucher */ function createPaymentMethod( uint256 _tokenIdSupply, PaymentMethod _paymentMethod, address _tokenPrice, address _tokenDeposits ) external; /** * @notice Mark voucher token that the payment was released * @param _tokenIdVoucher ID of the voucher token */ function setPaymentReleased(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token that the deposits were released * @param _tokenIdVoucher ID of the voucher token */ function setDepositsReleased(uint256 _tokenIdVoucher) external; /** * @notice Redemption of the vouchers promise * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function redeem(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Refunding a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function refund(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Issue a complain for a voucher * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher */ function complain(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal * @param _tokenIdVoucher ID of the voucher * @param _messageSender owner of the voucher set (seller) */ function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender) external; /** * @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange. * @param _tokenIdSupply ID of the voucher * @param _issuer owner of the voucher */ function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer) external returns (uint256); /** * @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder * @param _tokenIdSupply ID of the supply token (ERC-1155) * @param _issuer Address of the token's issuer * @param _holder Address of the recipient of the voucher (ERC-721) * @param _paymentMethod method being used for that particular order that needs to be fulfilled */ function fillOrder( uint256 _tokenIdSupply, address _issuer, address _holder, PaymentMethod _paymentMethod ) external; /** * @notice Mark voucher token as expired * @param _tokenIdVoucher ID of the voucher token */ function triggerExpiration(uint256 _tokenIdVoucher) external; /** * @notice Mark voucher token to the final status * @param _tokenIdVoucher ID of the voucher token */ function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external; /** * @notice Set the address of the new holder of a _tokenIdSupply on transfer * @param _tokenIdSupply _tokenIdSupply which will be transferred * @param _newSeller new holder of the supply */ function setSupplyHolderOnTransfer( uint256 _tokenIdSupply, address _newSeller ) external; /** * @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds) */ function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external; /** * @notice Set the address of the Boson Router contract * @param _bosonRouterAddress The address of the BR contract */ function setBosonRouterAddress(address _bosonRouterAddress) external; /** * @notice Set the address of the Cashier contract * @param _cashierAddress The address of the Cashier contract */ function setCashierAddress(address _cashierAddress) external; /** * @notice Set the address of the Vouchers token contract, an ERC721 contract * @param _voucherTokenAddress The address of the Vouchers token contract */ function setVoucherTokenAddress(address _voucherTokenAddress) external; /** * @notice Set the address of the Voucher Sets token contract, an ERC1155 contract * @param _voucherSetTokenAddress The address of the Voucher Sets token contract */ function setVoucherSetTokenAddress(address _voucherSetTokenAddress) external; /** * @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes. * @param _complainPeriod the new value for complain period (in number of seconds) */ function setComplainPeriod(uint256 _complainPeriod) external; /** * @notice Get the promise ID at specific index * @param _idx Index in the array of promise keys * @return Promise ID */ function getPromiseKey(uint256 _idx) external view returns (bytes32); /** * @notice Get the address of the token where the price for the supply is held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherPriceToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the address of the token where the deposits for the supply are held * @param _tokenIdSupply ID of the voucher token * @return Address of the token */ function getVoucherDepositToken(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get Buyer costs required to make an order for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Buyer's deposit) */ function getBuyerOrderCosts(uint256 _tokenIdSupply) external view returns (uint256, uint256); /** * @notice Get Seller deposit * @param _tokenIdSupply ID of the supply token * @return returns sellers deposit */ function getSellerDeposit(uint256 _tokenIdSupply) external view returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getIdSupplyFromVoucher(uint256 _tokenIdVoucher) external pure returns (uint256); /** * @notice Get the promise ID from a voucher token * @param _tokenIdVoucher ID of the voucher token * @return ID of the promise */ function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher) external view returns (bytes32); /** * @notice Get all necessary funds for a supply token * @param _tokenIdSupply ID of the supply token * @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit) */ function getOrderCosts(uint256 _tokenIdSupply) external view returns ( uint256, uint256, uint256 ); /** * @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account * @param _tokenSupplyId Token supply ID * @param _owner holder of the Token Supply * @return remaining quantity */ function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner) external view returns (uint256); /** * @notice Get the payment method for a particular _tokenIdSupply * @param _tokenIdSupply ID of the voucher supply token * @return payment method */ function getVoucherPaymentMethod(uint256 _tokenIdSupply) external view returns (PaymentMethod); /** * @notice Get the current status of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Status of the voucher (via enum) */ function getVoucherStatus(uint256 _tokenIdVoucher) external view returns ( uint8, bool, bool, uint256, uint256 ); /** * @notice Get the holder of a supply * @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise. * @return Address of the holder */ function getSupplyHolder(uint256 _tokenIdSupply) external view returns (address); /** * @notice Get the holder of a voucher * @param _tokenIdVoucher ID of the voucher token * @return Address of the holder */ function getVoucherHolder(uint256 _tokenIdVoucher) external view returns (address); /** * @notice Checks whether a voucher is in valid period for redemption (between start date and end date) * @param _tokenIdVoucher ID of the voucher token */ function isInValidityPeriod(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred * @param _tokenIdVoucher ID of the voucher token */ function isVoucherTransferable(uint256 _tokenIdVoucher) external view returns (bool); /** * @notice Get address of the Boson Router contract to which this contract points * @return Address of the Boson Router contract */ function getBosonRouterAddress() external view returns (address); /** * @notice Get address of the Cashier contract to which this contract points * @return Address of the Cashier contract */ function getCashierAddress() external view returns (address); /** * @notice Get the token nonce for a seller * @param _seller Address of the seller * @return The seller's */ function getTokenNonce(address _seller) external view returns (uint256); /** * @notice Get the current type Id * @return type Id */ function getTypeId() external view returns (uint256); /** * @notice Get the complain period * @return complain period */ function getComplainPeriod() external view returns (uint256); /** * @notice Get the cancel or fault period * @return cancel or fault period */ function getCancelFaultPeriod() external view returns (uint256); /** * @notice Get promise data not retrieved by other accessor functions * @param _promiseKey ID of the promise * @return promise data not returned by other accessor methods */ function getPromiseData(bytes32 _promiseKey) external view returns ( bytes32, uint256, uint256, uint256, uint256 ); /** * @notice Get the promise ID from a voucher set * @param _tokenIdSupply ID of the voucher token * @return ID of the promise */ function getPromiseIdFromSupplyId(uint256 _tokenIdSupply) external view returns (bytes32); /** * @notice Get the address of the Vouchers token contract, an ERC721 contract * @return Address of Vouchers contract */ function getVoucherTokenAddress() external view returns (address); /** * @notice Get the address of the VoucherSets token contract, an ERC155 contract * @return Address of VoucherSets contract */ function getVoucherSetTokenAddress() external view returns (address); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; // Those are the payment methods we are using throughout the system. // Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise enum PaymentMethod { ETHETH, ETHTKN, TKNETH, TKNTKN } enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT} /* Status of the voucher in 8 bits: [6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL] */ uint8 constant ONE = 1; struct VoucherDetails { uint256 tokenIdSupply; uint256 tokenIdVoucher; address issuer; address holder; uint256 price; uint256 depositSe; uint256 depositBu; uint256 price2pool; uint256 deposit2pool; uint256 price2issuer; uint256 deposit2issuer; uint256 price2holder; uint256 deposit2holder; PaymentMethod paymentMethod; VoucherStatus currStatus; } struct VoucherStatus { uint8 status; bool isPaymentReleased; bool isDepositsReleased; uint256 complainPeriodStart; uint256 cancelFaultPeriodStart; } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state. * @param _status current status of a voucher. */ function isStateCommitted(uint8 _status) pure returns (bool) { return _status == determineStatus(0, VoucherState.COMMIT); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state. * @param _status current status of a voucher. */ function isStateRedemptionSigned(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state. * @param _status current status of a voucher. */ function isStateRefunded(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state. * @param _status current status of a voucher. */ function isStateExpired(uint8 _status) pure returns (bool) { return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE); } /** * @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at. * @param _status current status of a voucher. * @param _idx status to compare. */ function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) { return (_status >> uint8(_idx)) & ONE == 1; } /** * @notice Set voucher status. * @param _status previous status. * @param _changeIdx next status. */ function determineStatus(uint8 _status, VoucherState _changeIdx) pure returns (uint8) { return _status | (ONE << uint8(_changeIdx)); } // 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.7.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.7.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.7.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.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); }
Extract a standard non-fungible token ERC-721 from a supply stored in ERC-1155 Token ID is derived following the same principles for both ERC-1155 and ERC-721 _issuer The address of the token issuer _to The address of the token holder _tokenIdSupply ID of the token type return ID of the voucher token/calculate tokenIdset statusmint voucher NFT as ERC-721
function extract721( address _issuer, address _to, uint256 _tokenIdSupply ) internal returns (uint256) { uint256 voucherTokenId = _tokenIdSupply | ++typeCounters[_tokenIdSupply]; vouchersStatus[voucherTokenId].status = determineStatus( vouchersStatus[voucherTokenId].status, VoucherState.COMMIT ); vouchersStatus[voucherTokenId].isPaymentReleased = false; vouchersStatus[voucherTokenId].isDepositsReleased = false; IVouchers(voucherTokenAddress).mint(_to, voucherTokenId); return voucherTokenId; }
40,210
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./lib/Ownable.sol"; import "./lib/Pausable.sol"; import "./erc/ERC721Enumerable.sol"; import "./IDegens.sol"; import "./IFortress.sol"; import "./ITraits.sol"; import "./IGains.sol"; contract Degens is IDegens, ERC721Enumerable, Ownable, Pausable { // mint price uint256 public MINT_PRICE = .069420 ether; // max number of tokens that can be minted - 50000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; bool isOGMintEnabled = true; bool isNFTOwnerWLEnabled = false; bool isPublicSaleEnabled = false; mapping(address => uint256) public whitelists; address[11] public extNftContractAddressWhitelists; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => IDegens.Degen) public tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; //eff ajwalkers algo uint8[8][4] rarities; // reference to the fortress for choosing random zombie thieves IFortress public fortress; // reference to $Gains for burning on mint IGains public gains; // reference to Traits ITraits public traits; /** * instantiates contract and rarity tables */ constructor(address _gains, address _traits, uint256 _maxTokens) ERC721("Game of Degens", 'GOD') { gains = IGains(_gains); traits = ITraits(_traits); MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; //accessories //clothes //eyes //background //mouth //body //hairdo //alphaIndex //bull rarities[0] = [16, 13, 9, 23, 9, 10, 0, 0]; //bear rarities[1] = [16, 9, 3, 23, 6, 8, 0, 0]; //ape rarities[2] = [16, 8, 4, 23, 8, 7, 0, 0]; //zombie rarities[3] = [16, 13, 3, 23, 0, 1, 7, 4]; //neotoken extNftContractAddressWhitelists[0] = 0x86357A19E5537A8Fba9A004E555713BC943a66C0; //fluf extNftContractAddressWhitelists[1] = 0xCcc441ac31f02cD96C153DB6fd5Fe0a2F4e6A68d; //ppg extNftContractAddressWhitelists[2] = 0xBd3531dA5CF5857e7CfAA92426877b022e612cf8; //doggy extNftContractAddressWhitelists[3] = 0xF4ee95274741437636e748DdAc70818B4ED7d043; //doodle extNftContractAddressWhitelists[4] = 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e; //toadz extNftContractAddressWhitelists[5] = 0x1CB1A5e65610AEFF2551A50f76a87a7d3fB649C6; //cool extNftContractAddressWhitelists[6] = 0x1A92f7381B9F03921564a437210bB9396471050C; //kongz extNftContractAddressWhitelists[7] = 0x57a204AA1042f6E66DD7730813f4024114d74f37; //bayc extNftContractAddressWhitelists[8] = 0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D; //cryptopunkz extNftContractAddressWhitelists[9] = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; //mayc extNftContractAddressWhitelists[10] = 0x60E4d786628Fea6478F785A6d7e704777c86a7c6; } /** EXTERNAL */ function addOGsToWhitelist(address[] calldata addressArrays) external onlyOwner { uint256 addylength = addressArrays.length; for (uint256 i; i < addylength; i++) { whitelists[addressArrays[i]] = 1; } } function enableOGWLMint() external onlyOwner { isOGMintEnabled = true; isNFTOwnerWLEnabled = false; isPublicSaleEnabled = false; MINT_PRICE = .069420 ether; } function enableOtherNFTOwnerWLMint() external onlyOwner { isOGMintEnabled = false; isNFTOwnerWLEnabled = true; isPublicSaleEnabled = false; MINT_PRICE = .069420 ether; } function enablePublicMint() external onlyOwner { isOGMintEnabled = false; isNFTOwnerWLEnabled = false; isPublicSaleEnabled = true; MINT_PRICE = .069420 ether; } function getNFTBalance(address contrct, address acc) internal view returns (uint256 balance){ balance = 0; try IERC721(contrct).balanceOf(acc) returns (uint256 _balance){ balance = _balance; } catch { balance = 0; } return balance; } function isWLBasisNFTOwner(address acc) external view returns (bool) { for (uint i = 0; i < extNftContractAddressWhitelists.length; i++) { if (getNFTBalance(extNftContractAddressWhitelists[i], acc) > 0) { return true; } } return false; } function isWLBasisOG(address acc) external view returns (bool){ return whitelists[acc] == 1; } function getMintMode() external view returns (bool, bool, bool){ return (isOGMintEnabled, isNFTOwnerWLEnabled, isPublicSaleEnabled); } /** * mint a token - 90% Degens, 10% Zombies * The first 20% are free to claim, the remaining cost $GAINS */ function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE <= msg.value, "Invalid payment amount"); if (!isPublicSaleEnabled) { if (isOGMintEnabled) { require(this.isWLBasisOG(_msgSender()), "Only open for whitelist"); } else if (isNFTOwnerWLEnabled) { require(this.isWLBasisNFTOwner(_msgSender()), "Only open for special peeps at the moment"); } } } else { require(msg.value == 0); } uint256 totalGainsCost = 0; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); generate(minted, seed); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); } else { _safeMint(address(fortress), minted); tokenIds[i] = minted; } totalGainsCost += mintCost(minted); } if (totalGainsCost > 0) gains.burn(_msgSender(), totalGainsCost); if (stake) fortress.addDegensToFortressAndHorde(_msgSender(), tokenIds); } /** * the first 20% are paid in ETH * the next 20% are 20000 $GAINS * the next 40% are 40000 $GAINS * the final 20% are 80000 $GAINS * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether; if (tokenId <= MAX_TOKENS * 4 / 5) return 40000 ether; return 80000 ether; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override(IERC721, ERC721) { // Hardcode the fortress's approval so that users don't have to waste gas approving if (_msgSender() != address(fortress)) require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (IDegens.Degen memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType, uint8 degenType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[degenType][traitType]); return trait; } /** * the first 20% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked zombie * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the zombie thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = fortress.randomZombieOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (IDegens.Degen memory t) { bool isZombie = uint8((seed & 0xFFFF) % 10) == 0; t.degenType = isZombie ? 3 : uint8((seed & 0xFFFF) % 3); seed >>= 16; t.accessories = selectTrait(uint16(seed & 0xFFFF), 0, t.degenType); seed >>= 16; t.clothes = selectTrait(uint16(seed & 0xFFFF), 1, t.degenType); seed >>= 16; t.eyes = selectTrait(uint16(seed & 0xFFFF), 2, t.degenType); seed >>= 16; t.background = selectTrait(uint16(seed & 0xFFFF), 3, 0); seed >>= 16; t.body = selectTrait(uint16(seed & 0xFFFF), 5, t.degenType); if (!this.isZombies(t)) { seed >>= 16; t.mouth = selectTrait(uint16(seed & 0xFFFF), 4, t.degenType); } else { seed >>= 16; t.hairdo = selectTrait(uint16(seed & 0xFFFF), 6, t.degenType); seed >>= 16; t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 7, t.degenType); } return t; } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(IDegens.Degen memory s) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( s.degenType, s.accessories, s.clothes, s.eyes, s.background, s.mouth, s.body, s.hairdo, s.alphaIndex ) )); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } /** READ */ function getTokenTraits(uint256 tokenId) external view override returns (Degen memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } function isBull(Degen memory _degen) external pure override returns (bool){ return _degen.degenType == 0; } function isBears(Degen memory _degen) external pure override returns (bool){ return _degen.degenType == 1; } function isApes(Degen memory _degen) external pure override returns (bool){ return _degen.degenType == 2; } function isZombies(Degen memory _degen) external pure override returns (bool){ return _degen.degenType == 3; } function getNFTName(Degen memory _degen) external view override returns (string memory){ if (this.isZombies(_degen)) { return "Zombie"; } else { return "Degen"; } } function getDegenTypeName(Degen memory _degen) external view override returns (string memory){ if (this.isBull(_degen)) { return "Bull"; } else if (this.isBears(_degen)) { return "Bear"; } else if (this.isZombies(_degen)) { return "Zombie"; } else if (this.isApes(_degen)) { return "Ape"; } return "Error"; } function getNFTGeneration(uint256 tokenId) external pure returns (string memory){ if (tokenId >= 1 && tokenId < 3333) { return "Gen 0"; } else if (tokenId >= 3333 && tokenId < 6666) { return "Gen 1"; } else if (tokenId >= 6666 && tokenId < 13333) { return "Gen 2"; } else if (tokenId >= 13333 && tokenId <= 16666) { return "Gen X"; } return "Error"; } /** ADMIN */ /** * called after deployment so that the contract can get random zombie thieves * @param _fortress the address of the fortress */ function setFortressContractAddress(address _fortress) external onlyOwner { fortress = IFortress(_fortress); } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** RENDER */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return traits.tokenURI(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import ".././ierc/IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import ".././ierc/IERC721.sol"; import ".././ierc/IERC721Receiver.sol"; import ".././ierc/IERC721Metadata.sol"; import ".././lib/Address.sol"; import ".././lib/Context.sol"; import ".././lib/Strings.sol"; import ".././erc/ERC165.sol"; import "../lib/ReentrancyGuard.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, ReentrancyGuard { 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 nonReentrant { _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 ".././ierc/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 LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IGains { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IFortress { function addDegensToFortressAndHorde(address account, uint16[] calldata tokenIds) external; function randomZombieOwner(uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./ierc/IERC721.sol"; interface IDegens is IERC721 { // struct to store each token's traits struct Degen { uint8 degenType; uint8 accessories; uint8 clothes; uint8 eyes; uint8 background; uint8 mouth; uint8 body; uint8 hairdo; uint8 alphaIndex; } function getDegenTypeName(Degen memory _degen) external view returns (string memory); function getNFTName(Degen memory _degen) external view returns (string memory); function getNFTGeneration(uint256 tokenId) external pure returns (string memory); function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (Degen memory); function isBull(Degen memory _character) external pure returns (bool); function isBears(Degen memory _character) external pure returns (bool); function isZombies(Degen memory _character) external pure returns (bool); function isApes(Degen memory _character) external pure returns (bool); }
generates traits for a specific token, checking to make sure it's unique tokenId the id of the token to generate traits for seed a pseudorandom 256 bit number to derive traits from return t - a struct of traits for the given token ID/
function generate(uint256 tokenId, uint256 seed) internal returns (IDegens.Degen memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); }
6,855,762
./partial_match/3/0x93aE15BC2454C138e79F3F9EB26F9743c0c25C77/sources/pool.sol
reset the option/ reset the contract substract issueable _ethersToIssue
function _renewOption(Option option, uint etherPrice) internal override { uint optionSupply = ethersToIssue .mul(utilizationRate) .div(100) .div(_options.length); option.resetOption(etherPrice, optionSupply); ethersToIssue = ethersToIssue.sub(optionSupply); }
5,151,252
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./interfaces/IDebtRedemption.sol"; import "./interfaces/IUARForDollarsCalculator.sol"; import "./interfaces/ICouponsForDollarsCalculator.sol"; import "./interfaces/IDollarMintingCalculator.sol"; import "./interfaces/IExcessDollarsDistributor.sol"; import "./TWAPOracle.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./UbiquityAlgorithmicDollar.sol"; import "./UbiquityAutoRedeem.sol"; import "./UbiquityAlgorithmicDollarManager.sol"; import "./DebtCoupon.sol"; /// @title A basic debt issuing and redemption mechanism for coupon holders /// @notice Allows users to burn their uAD in exchange for coupons /// redeemable in the future /// @notice Allows users to redeem individual debt coupons or batch redeem /// coupons on a first-come first-serve basis contract DebtCouponManager is ERC165, IERC1155Receiver { using SafeERC20 for IERC20Ubiquity; UbiquityAlgorithmicDollarManager public manager; //the amount of dollars we minted this cycle, so we can calculate delta. // should be reset to 0 when cycle ends uint256 public dollarsMintedThisCycle; bool public debtCycle; uint256 public blockHeightDebt; uint256 public couponLengthBlocks; uint256 public expiredCouponConvertionRate = 2; event ExpiredCouponConvertionRateChanged( uint256 newRate, uint256 previousRate ); event CouponLengthChanged( uint256 newCouponLengthBlocks, uint256 previousCouponLengthBlocks ); modifier onlyCouponManager() { require( manager.hasRole(manager.COUPON_MANAGER_ROLE(), msg.sender), "Caller is not a coupon manager" ); _; } /// @param _manager the address of the manager contract so we can fetch variables /// @param _couponLengthBlocks how many blocks coupons last. can't be changed /// once set (unless migrated) constructor(address _manager, uint256 _couponLengthBlocks) { manager = UbiquityAlgorithmicDollarManager(_manager); couponLengthBlocks = _couponLengthBlocks; } function setExpiredCouponConvertionRate(uint256 rate) external onlyCouponManager { emit ExpiredCouponConvertionRateChanged( rate, expiredCouponConvertionRate ); expiredCouponConvertionRate = rate; } function setCouponLength(uint256 _couponLengthBlocks) external onlyCouponManager { emit CouponLengthChanged(_couponLengthBlocks, couponLengthBlocks); couponLengthBlocks = _couponLengthBlocks; } /// @dev called when a user wants to burn UAD for debt coupon. /// should only be called when oracle is below a dollar /// @param amount the amount of dollars to exchange for coupons function exchangeDollarsForDebtCoupons(uint256 amount) external returns (uint256) { uint256 twapPrice = _getTwapPrice(); require(twapPrice < 1 ether, "Price must be below 1 to mint coupons"); DebtCoupon debtCoupon = DebtCoupon(manager.debtCouponAddress()); debtCoupon.updateTotalDebt(); //we are in a down cycle so reset the cycle counter // and set the blockHeight Debt if (!debtCycle) { debtCycle = true; blockHeightDebt = block.number; dollarsMintedThisCycle = 0; } ICouponsForDollarsCalculator couponCalculator = ICouponsForDollarsCalculator( manager.couponCalculatorAddress() ); uint256 couponsToMint = couponCalculator.getCouponAmount(amount); // we burn user's dollars. UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( msg.sender, amount ); uint256 expiryBlockNumber = block.number + (couponLengthBlocks); debtCoupon.mintCoupons(msg.sender, couponsToMint, expiryBlockNumber); //give the caller the block number of the minted nft return expiryBlockNumber; } /// @dev called when a user wants to burn UAD for uAR. /// should only be called when oracle is below a dollar /// @param amount the amount of dollars to exchange for uAR /// @return amount of auto redeem tokens minted function exchangeDollarsForUAR(uint256 amount) external returns (uint256) { uint256 twapPrice = _getTwapPrice(); require(twapPrice < 1 ether, "Price must be below 1 to mint uAR"); DebtCoupon debtCoupon = DebtCoupon(manager.debtCouponAddress()); debtCoupon.updateTotalDebt(); //we are in a down cycle so reset the cycle counter // and set the blockHeight Debt if (!debtCycle) { debtCycle = true; blockHeightDebt = block.number; dollarsMintedThisCycle = 0; } IUARForDollarsCalculator uarCalculator = IUARForDollarsCalculator( manager.uarCalculatorAddress() ); uint256 uarToMint = uarCalculator.getUARAmount(amount, blockHeightDebt); // we burn user's dollars. UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( msg.sender, amount ); // mint uAR UbiquityAutoRedeem autoRedeemToken = UbiquityAutoRedeem( manager.autoRedeemTokenAddress() ); autoRedeemToken.mint(msg.sender, uarToMint); //give minted uAR amount return uarToMint; } /// @dev uses the current coupons for dollars calculation to get coupons for dollars /// @param amount the amount of dollars to exchange for coupons function getCouponsReturnedForDollars(uint256 amount) external view returns (uint256) { ICouponsForDollarsCalculator couponCalculator = ICouponsForDollarsCalculator( manager.couponCalculatorAddress() ); return couponCalculator.getCouponAmount(amount); } /// @dev uses the current uAR for dollars calculation to get uAR for dollars /// @param amount the amount of dollars to exchange for uAR function getUARReturnedForDollars(uint256 amount) external view returns (uint256) { IUARForDollarsCalculator uarCalculator = IUARForDollarsCalculator( manager.uarCalculatorAddress() ); return uarCalculator.getUARAmount(amount, blockHeightDebt); } /// @dev should be called by this contract only when getting coupons to be burnt function onERC1155Received( address operator, address, uint256, uint256, bytes calldata ) external view override returns (bytes4) { if (manager.hasRole(manager.COUPON_MANAGER_ROLE(), operator)) { //allow the transfer since it originated from this contract return bytes4( keccak256( "onERC1155Received(address,address,uint256,uint256,bytes)" ) ); } else { //reject the transfer return ""; } } /// @dev this method is never called by the contract so if called, /// it was called by someone else -> revert. function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external pure override returns (bytes4) { //reject the transfer return ""; } /// @dev let debt holder burn expired coupons for UGOV. Doesn't make TWAP > 1 check. /// @param id the timestamp of the coupon /// @param amount the amount of coupons to redeem /// @return uGovAmount amount of UGOV tokens minted to debt holder function burnExpiredCouponsForUGOV(uint256 id, uint256 amount) public returns (uint256 uGovAmount) { // Check whether debt coupon hasn't expired --> Burn debt coupons. DebtCoupon debtCoupon = DebtCoupon(manager.debtCouponAddress()); require(id <= block.number, "Coupon has not expired"); require( debtCoupon.balanceOf(msg.sender, id) >= amount, "User not enough coupons" ); debtCoupon.burnCoupons(msg.sender, amount, id); // Mint UGOV tokens to this contract. Transfer UGOV tokens to msg.sender i.e. debt holder IERC20Ubiquity uGOVToken = IERC20Ubiquity( manager.governanceTokenAddress() ); uGovAmount = amount / expiredCouponConvertionRate; uGOVToken.mint(msg.sender, uGovAmount); } // TODO should we leave it ? /// @dev Lets debt holder burn coupons for auto redemption. Doesn't make TWAP > 1 check. /// @param id the timestamp of the coupon /// @param amount the amount of coupons to redeem /// @return amount of auto redeem pool tokens (i.e. LP tokens) minted to debt holder function burnCouponsForAutoRedemption(uint256 id, uint256 amount) public returns (uint256) { // Check whether debt coupon hasn't expired --> Burn debt coupons. DebtCoupon debtCoupon = DebtCoupon(manager.debtCouponAddress()); require(id > block.timestamp, "Coupon has expired"); require( debtCoupon.balanceOf(msg.sender, id) >= amount, "User not enough coupons" ); debtCoupon.burnCoupons(msg.sender, amount, id); // Mint LP tokens to this contract. Transfer LP tokens to msg.sender i.e. debt holder UbiquityAutoRedeem autoRedeemToken = UbiquityAutoRedeem( manager.autoRedeemTokenAddress() ); autoRedeemToken.mint(address(this), amount); autoRedeemToken.transfer(msg.sender, amount); return autoRedeemToken.balanceOf(msg.sender); } /// @dev Exchange auto redeem pool token for uAD tokens. /// @param amount Amount of uAR tokens to burn in exchange for uAD tokens. /// @return amount of unredeemed uAR function burnAutoRedeemTokensForDollars(uint256 amount) public returns (uint256) { uint256 twapPrice = _getTwapPrice(); require(twapPrice > 1 ether, "Price must be above 1 to auto redeem"); if (debtCycle) { debtCycle = false; } UbiquityAutoRedeem autoRedeemToken = UbiquityAutoRedeem( manager.autoRedeemTokenAddress() ); require( autoRedeemToken.balanceOf(msg.sender) >= amount, "User doesn't have enough auto redeem pool tokens." ); UbiquityAlgorithmicDollar uAD = UbiquityAlgorithmicDollar( manager.dollarTokenAddress() ); uint256 maxRedeemableUAR = uAD.balanceOf(address(this)); if (maxRedeemableUAR <= 0) { mintClaimableDollars(); maxRedeemableUAR = uAD.balanceOf(address(this)); } uint256 uarToRedeem = amount; if (amount > maxRedeemableUAR) { uarToRedeem = maxRedeemableUAR; } autoRedeemToken.burnFrom(msg.sender, uarToRedeem); uAD.transfer(msg.sender, uarToRedeem); return amount - uarToRedeem; } /// @param id the block number of the coupon /// @param amount the amount of coupons to redeem /// @return amount of unredeemed coupons function redeemCoupons(uint256 id, uint256 amount) public returns (uint256) { uint256 twapPrice = _getTwapPrice(); require(twapPrice > 1 ether, "Price must be above 1 to redeem coupons"); if (debtCycle) { debtCycle = false; } DebtCoupon debtCoupon = DebtCoupon(manager.debtCouponAddress()); require(id > block.number, "Coupon has expired"); require( debtCoupon.balanceOf(msg.sender, id) >= amount, "User not enough coupons" ); mintClaimableDollars(); UbiquityAlgorithmicDollar uAD = UbiquityAlgorithmicDollar( manager.dollarTokenAddress() ); UbiquityAutoRedeem autoRedeemToken = UbiquityAutoRedeem( manager.autoRedeemTokenAddress() ); // uAR have a priority on uDEBT coupon holder require( autoRedeemToken.totalSupply() <= uAD.balanceOf(address(this)), "There aren't enough uAD to redeem currently" ); uint256 maxRedeemableCoupons = uAD.balanceOf(address(this)) - autoRedeemToken.totalSupply(); uint256 couponsToRedeem = amount; if (amount > maxRedeemableCoupons) { couponsToRedeem = maxRedeemableCoupons; } require( uAD.balanceOf(address(this)) > 0, "There aren't any uAD to redeem currently" ); // debtCouponManager must be an operator to transfer on behalf of msg.sender debtCoupon.burnCoupons(msg.sender, couponsToRedeem, id); uAD.transfer(msg.sender, couponsToRedeem); return amount - (couponsToRedeem); } function mintClaimableDollars() public { DebtCoupon debtCoupon = DebtCoupon(manager.debtCouponAddress()); debtCoupon.updateTotalDebt(); // uint256 twapPrice = _getTwapPrice(); //unused variable. Why here? uint256 totalMintableDollars = IDollarMintingCalculator( manager.dollarMintingCalculatorAddress() ).getDollarsToMint(); uint256 dollarsToMint = totalMintableDollars - (dollarsMintedThisCycle); //update the dollars for this cycle dollarsMintedThisCycle = totalMintableDollars; UbiquityAlgorithmicDollar uAD = UbiquityAlgorithmicDollar( manager.dollarTokenAddress() ); // uAD dollars should be minted to address(this) uAD.mint(address(this), dollarsToMint); UbiquityAutoRedeem autoRedeemToken = UbiquityAutoRedeem( manager.autoRedeemTokenAddress() ); uint256 currentRedeemableBalance = uAD.balanceOf(address(this)); uint256 totalOutstandingDebt = debtCoupon.getTotalOutstandingDebt() + autoRedeemToken.totalSupply(); if (currentRedeemableBalance > totalOutstandingDebt) { uint256 excessDollars = currentRedeemableBalance - (totalOutstandingDebt); IExcessDollarsDistributor dollarsDistributor = IExcessDollarsDistributor( manager.getExcessDollarsDistributor(address(this)) ); //transfer excess dollars to the distributor and tell it to distribute uAD.transfer( manager.getExcessDollarsDistributor(address(this)), excessDollars ); dollarsDistributor.distributeDollars(); } } function _getTwapPrice() internal returns (uint256) { TWAPOracle(manager.twapOracleAddress()).update(); return TWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
should be called by this contract only when getting coupons to be burntallow the transfer since it originated from this contractreject the transfer
function onERC1155Received( address operator, address, uint256, uint256, bytes calldata ) external view override returns (bytes4) { if (manager.hasRole(manager.COUPON_MANAGER_ROLE(), operator)) { return bytes4( keccak256( "onERC1155Received(address,address,uint256,uint256,bytes)" ) ); return ""; } }
12,729,405
// Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.19; contract ERC20Token { /* 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 constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) 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 constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.2'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws var previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require(msg.sender == owner); _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() public { owner = msg.sender; } address public newOwner; /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } contract TokenContribution is Owned, TokenController { using SafeMath for uint256; uint256 constant public maxSupply = 10000000 * 10**8; // Half of the max supply. 50% for ico uint256 constant public saleLimit = 5000000 * 10**8; uint256 constant public maxGasPrice = 50000000000; uint256 constant public maxCallFrequency = 100; MiniMeToken public token; address public destTokensTeam; address public destTokensReserve; address public destTokensBounties; address public destTokensAirdrop; address public destTokensAdvisors; address public destTokensEarlyInvestors; uint256 public totalTokensGenerated; uint256 public finalizedBlock; uint256 public finalizedTime; uint256 public generatedTokensSale; mapping(address => uint256) public lastCallBlock; modifier initialized() { require(address(token) != 0x0); _; } function TokenContribution() public { } /// @notice The owner of this contract can change the controller of the token /// Please, be sure that the owner is a trusted agent or 0x0 address. /// @param _newController The address of the new controller function changeController(address _newController) public onlyOwner { token.changeController(_newController); ControllerChanged(_newController); } /// @notice This method should be called by the owner before the contribution /// period starts This initializes most of the parameters function initialize( address _token, address _destTokensReserve, address _destTokensTeam, address _destTokensBounties, address _destTokensAirdrop, address _destTokensAdvisors, address _destTokensEarlyInvestors ) public onlyOwner { // Initialize only once require(address(token) == 0x0); token = MiniMeToken(_token); require(token.totalSupply() == 0); require(token.controller() == address(this)); require(token.decimals() == 8); require(_destTokensReserve != 0x0); destTokensReserve = _destTokensReserve; require(_destTokensTeam != 0x0); destTokensTeam = _destTokensTeam; require(_destTokensBounties != 0x0); destTokensBounties = _destTokensBounties; require(_destTokensAirdrop != 0x0); destTokensAirdrop = _destTokensAirdrop; require(_destTokensAdvisors != 0x0); destTokensAdvisors = _destTokensAdvisors; require(_destTokensEarlyInvestors != 0x0); destTokensEarlyInvestors= _destTokensEarlyInvestors; } ////////// // MiniMe Controller functions ////////// function proxyPayment(address) public payable returns (bool) { return false; } function onTransfer(address _from, address, uint256) public returns (bool) { return transferable(_from); } function onApprove(address _from, address, uint256) public returns (bool) { return transferable(_from); } function transferable(address _from) internal view returns (bool) { // Allow the exchanger to work from the beginning if (finalizedTime == 0) return false; return (getTime() > finalizedTime) || (_from == owner); } function generate(address _th, uint256 _amount) public onlyOwner { require(generatedTokensSale.add(_amount) <= saleLimit); require(_amount > 0); generatedTokensSale = generatedTokensSale.add(_amount); token.generateTokens(_th, _amount); NewSale(_th, _amount); } // NOTE on Percentage format // Right now, Solidity does not support decimal numbers. (This will change very soon) // So in this contract we use a representation of a percentage that consist in // expressing the percentage in "x per 10**18" // This format has a precision of 16 digits for a percent. // Examples: // 3% = 3*(10**16) // 100% = 100*(10**16) = 10**18 // // To get a percentage of a value we do it by first multiplying it by the percentage in (x per 10^18) // and then divide it by 10**18 // // Y * X(in x per 10**18) // X% of Y = ------------------------- // 100(in x per 10**18) // /// @notice This method will can be called by the owner before the contribution period /// end or by anybody after the `endBlock`. This method finalizes the contribution period /// by creating the remaining tokens and transferring the controller to the configured /// controller. function finalize() public initialized onlyOwner { require(finalizedBlock == 0); finalizedBlock = getBlockNumber(); finalizedTime = now; // Percentage to sale // uint256 percentageToCommunity = percent(50); uint256 percentageToTeam = percent(18); uint256 percentageToReserve = percent(8); uint256 percentageToBounties = percent(13); uint256 percentageToAirdrop = percent(2); uint256 percentageToAdvisors = percent(7); uint256 percentageToEarlyInvestors = percent(2); // // percentageToBounties // bountiesTokens = ----------------------- * maxSupply // percentage(100) // assert(token.generateTokens( destTokensBounties, maxSupply.mul(percentageToBounties).div(percent(100)))); // // percentageToReserve // reserveTokens = ----------------------- * maxSupply // percentage(100) // assert(token.generateTokens( destTokensReserve, maxSupply.mul(percentageToReserve).div(percent(100)))); // // percentageToTeam // teamTokens = ----------------------- * maxSupply // percentage(100) // assert(token.generateTokens( destTokensTeam, maxSupply.mul(percentageToTeam).div(percent(100)))); // // percentageToAirdrop // airdropTokens = ----------------------- * maxSupply // percentage(100) // assert(token.generateTokens( destTokensAirdrop, maxSupply.mul(percentageToAirdrop).div(percent(100)))); // // percentageToAdvisors // advisorsTokens = ----------------------- * maxSupply // percentage(100) // assert(token.generateTokens( destTokensAdvisors, maxSupply.mul(percentageToAdvisors).div(percent(100)))); // // percentageToEarlyInvestors // advisorsTokens = ------------------------------ * maxSupply // percentage(100) // assert(token.generateTokens( destTokensEarlyInvestors, maxSupply.mul(percentageToEarlyInvestors).div(percent(100)))); Finalized(); } function percent(uint256 p) internal pure returns (uint256) { return p.mul(10 ** 16); } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) internal view returns (bool) { if (_addr == 0) return false; uint256 size; assembly { size := extcodesize(_addr) } return (size > 0); } ////////// // Constant functions ////////// /// @return Total tokens issued in weis. function tokensIssued() public view returns (uint256) { return token.totalSupply(); } ////////// // Testing specific methods ////////// /// @notice This function is overridden by the test Mocks. function getBlockNumber() internal view returns (uint256) { return block.number; } /// @notice This function is overrided by the test Mocks. function getTime() internal view returns (uint256) { return now; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { if (token.controller() == address(this)) { token.claimTokens(_token); } if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Token erc20token = ERC20Token(_token); uint256 balance = erc20token.balanceOf(this); erc20token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event ControllerChanged(address indexed _newController); event NewSale(address indexed _th, uint256 _amount); event Finalized(); } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function percent(uint a, uint b) internal pure returns (uint) { return b * a / 100; } } contract AirdropTokensHolder is Owned { using SafeMath for uint256; uint256 public collectedTokens; TokenContribution public crowdsale; MiniMeToken public miniMeToken; function AirdropTokensHolder(address _owner, address _crowdsale, address _miniMeToken) public { owner = _owner; crowdsale = TokenContribution(_crowdsale); miniMeToken = MiniMeToken(_miniMeToken); } /// @notice The owner will call this method to extract the tokens function collectTokens() public onlyOwner { uint256 balance = miniMeToken.balanceOf(address(this)); uint256 total = collectedTokens.add(balance); uint256 finalizedTime = crowdsale.finalizedTime(); require(finalizedTime > 0 && getTime() > finalizedTime.add(months(3))); uint256 canExtract = 0; if (getTime() <= finalizedTime.add(months(6))) { require(collectedTokens < total.percent(25)); canExtract = total.percent(25); } else if (getTime() > finalizedTime.add(months(6)) && getTime() <= finalizedTime.add(months(9))) { require(collectedTokens < total.percent(50)); canExtract = total.percent(50); } else if (getTime() > finalizedTime.add(months(9)) && getTime() <= finalizedTime.add(months(12))) { require(collectedTokens < total.percent(75)); canExtract = total.percent(75); } else { canExtract = total; } canExtract = canExtract.sub(collectedTokens); if (canExtract > balance) { canExtract = balance; } collectedTokens = collectedTokens.add(canExtract); miniMeToken.transfer(owner, canExtract); TokensWithdrawn(owner, canExtract); } function months(uint256 m) internal pure returns (uint256) { return m.mul(30 days); } function getTime() internal view returns (uint256) { return now; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { require(_token != address(miniMeToken)); if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Token token = ERC20Token(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event TokensWithdrawn(address indexed _holder, uint256 _amount); }
The owner will call this method to extract the tokens
function collectTokens() public onlyOwner { uint256 balance = miniMeToken.balanceOf(address(this)); uint256 total = collectedTokens.add(balance); uint256 finalizedTime = crowdsale.finalizedTime(); require(finalizedTime > 0 && getTime() > finalizedTime.add(months(3))); uint256 canExtract = 0; if (getTime() <= finalizedTime.add(months(6))) { require(collectedTokens < total.percent(25)); canExtract = total.percent(25); require(collectedTokens < total.percent(50)); canExtract = total.percent(50); require(collectedTokens < total.percent(75)); canExtract = total.percent(75); canExtract = total; } canExtract = canExtract.sub(collectedTokens); if (canExtract > balance) { canExtract = balance; } collectedTokens = collectedTokens.add(canExtract); miniMeToken.transfer(owner, canExtract); TokensWithdrawn(owner, canExtract); }
335,955
./partial_match/1/0x755d1BBDD9929889Fe1376C65682f57BF270A25c/sources/contracts/erc721/ERC721EditionsDFS.sol
See {IERC721EditionMint-mintOneToRecipients}/
function mintOneToRecipients(uint256 editionId, address[] memory recipients) external onlyMinter nonReentrant returns (uint256) { if (_mintFrozen == 1) { _revert(MintFrozen.selector); } if (!_editionExists(editionId)) { _revert(EditionDoesNotExist.selector); } return _mintEditions(editionId, recipients, 1); }
16,128,529
./partial_match/1/0x85cdDcE5C1889D84e10d97074b7Af007f2CaDCC5/sources/BankrollNetworkStackPlus.sol
Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethToSpend) public pure returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethToSpend, entryFee_), 100); uint256 _taxedeth = SafeMath.sub(_ethToSpend, _dividends); uint256 _amountOfTokens = _taxedeth; return _amountOfTokens; }
11,023,182
./full_match/5/0xcF7AE0Afae903FE22cfEaD4C091B05ABC54c557b/sources/contracts/libraries/LibDiamond.sol
can't remove immutable functions -- functions defined directly in the diamond
function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { DiamondStorage storage ds = diamondStorage(); uint256 selectorCount = ds.selectors.length; if(_facetAddress != address(0)) { revert RemoveFacetAddressMustBeZeroAddress(_facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; FacetAddressAndSelectorPosition memory oldFacetAddressAndSelectorPosition = ds.facetAddressAndSelectorPosition[selector]; if(oldFacetAddressAndSelectorPosition.facetAddress == address(0)) { revert CannotRemoveFunctionThatDoesNotExist(selector); } if(oldFacetAddressAndSelectorPosition.facetAddress == address(this)) { revert CannotRemoveImmutableFunction(selector); } if (oldFacetAddressAndSelectorPosition.selectorPosition != selectorCount) { bytes4 lastSelector = ds.selectors[selectorCount]; ds.selectors[oldFacetAddressAndSelectorPosition.selectorPosition] = lastSelector; ds.facetAddressAndSelectorPosition[lastSelector].selectorPosition = oldFacetAddressAndSelectorPosition.selectorPosition; } delete ds.facetAddressAndSelectorPosition[selector]; } }
1,901,785
./partial_match/1/0x8DF465690353c845Dcb2e6456fE90851753bD37B/sources/Unik_Watch_NEOPULSE.sol
Set the state of the public sale. value The new state of the public sale. Only authorized addresses can call this function./
function publicSaleState(bool value) public onlyAuthorized { publicSaleStarted = value; }
9,292,279
./full_match/4/0x083b33869354138482D50d2463Bd09FbD99b0bD2/sources/_pooltogether/pooltogether-contracts/contracts/prize-strategy/PeriodicPrizeStrategy.sol
Initializes a new strategy _trustedForwarder the GSN v2 trusted forwarder to use _prizePeriodStart The starting timestamp of the prize period. _prizePeriodSeconds The duration of the prize period in seconds _prizePool The prize pool to award _ticket The ticket to use to draw winners _sponsorship The sponsorship token _rng The RNG service to use
function initialize ( address _trustedForwarder, uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, IERC20Upgradeable[] memory externalErc20Awards ) public initializer { require(_prizePeriodSeconds > 0, "PeriodicPrizeStrategy/prize-period-greater-than-zero"); require(address(_prizePool) != address(0), "PeriodicPrizeStrategy/prize-pool-not-zero"); require(address(_ticket) != address(0), "PeriodicPrizeStrategy/ticket-not-zero"); require(address(_sponsorship) != address(0), "PeriodicPrizeStrategy/sponsorship-not-zero"); require(address(_rng) != address(0), "PeriodicPrizeStrategy/rng-not-zero"); prizePool = _prizePool; ticket = _ticket; rng = _rng; sponsorship = _sponsorship; trustedForwarder = _trustedForwarder; __Ownable_init(); Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); externalErc20s.initialize(); for (uint256 i = 0; i < externalErc20Awards.length; i++) { _addExternalErc20Award(externalErc20Awards[i]); } prizePeriodSeconds = _prizePeriodSeconds; prizePeriodStartedAt = _prizePeriodStart; externalErc721s.initialize(); emit Initialized( _trustedForwarder, _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, externalErc20Awards ); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); }
12,376,555
pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; import "./FixedPoint.sol"; contract Dip is ERC20 { using SafeMath for uint256; IUniswapV2Router02 public UniswapV2Router02 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); private address _targetToken; private address _baseToken; private address _targetPair; private address _dipPair; private address _protocolFeeWallet; private address _protocolFee; private bool _predip = true; private uint256 _startTime; private uint256 _initialSupply; private mapping (address => uint256) _shares; private mapping (address => mapping (address => uint256)) _shareAllowances; constructor(address targetToken, address baseToken, address protocolFeeWallet) ERC20('Dip V1', 'DIP-V1') { _targetToken = target; _baseToken = baseToken; _protocolFeeWallet = protocolFeeWallet; address uniswapFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; _targetPair = address(uint(keccak256(abi.encodePacked( hex'ff', uniswapFactory, keccak256(abi.encodePacked(targetToken, baseToken)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); _dipPair = address(uint(keccak256(abi.encodePacked( hex'ff', uniswapFactory, keccak256(abi.encodePacked(address(this), baseToken)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); _startTime = block.timestamp; } function balanceOf(address account) public view override returns (uint256) { if (_predip === true) { return _balances[account]; } if (_balances[account] > 0) { return FixedPoint.calculateMantissa( _balances[account], _initialSupply ); } return FixedPoint.multiplyUintByMantissa( _totalSupply, _shares[account] ); } function transfer(address recipient, uint256 amount) public override returns (bool) { if (_predip === true) { _transfer(_msgSender(), recipient, amount); return true; } if (shareCalculated[_msgSender()] === false) { _calculateShare(_msgSender()); } amount = _convertAmountToShare(amount); require(_shares[_msgSender()] >= amount, "Insufficient balance."); _shares[_msgSender()].sub(amount); _shares[recipient].add(amount); } function allowance(address owner, address spender) public view override returns (uint256) { if (_predip === true) { return _allowances[owner][spender]; } return FixedPoint.multiplyUintByMantissa( _totalSupply, _shareAllowances[owner][spender] ); } function approve(address spender, uint256 amount) public override returns (bool) { if (_predip === true) { _approve(_msgSender(), spender, amount); return true; } if (_balances[_msgSender()] > 0) { _calculateShare(_msgSender()); } amount = _convertAmountToShare(amount); _shareAllowances[_msgSender(), spender] = amount; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { if (_predip === true) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance") ); return true; } if (_balances[sender] > 0) { _calculateShare(sender); } amount = _convertAmountToShare(amount); require(_shares[sender] >= amount, "Insufficient balance."); _shares[sender].sub(amount); _shares[recipient].add(amount); } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { if (_predip === true) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } if (_balances[_msgSender()] > 0) { _calculateShare(_msgSender()); } addedValue = _convertAmountToShare(addedValue); _shareAllowances[_msgSender(), spender].add(addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { if (_predip === true) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } if (_balances[_msgSender()] > 0) { _calculateShare(_msgSender()); } subtractedValue = _convertAmountToShare(subtractedValue); _shareAllowances[_msgSender(), spender].sub(subtractedValue); } function swap(uint256 amountIn, uint256 amountOut, uint256 dipAmountOut) public { require(_predip === true, "The token distribution period is over."); IERC20(_targetToken).transferFrom(_msgSender(), address(this), amountIn); IERC20(_targetToken).approve(address(UniswapV2Router02), amountIn); address[] memory path = new address[](2); path[0] = address(_targetToken); path[1] = address(_baseToken); uint[] memory amounts = UniswapV2Router02.swapExactTokensForTokens( amountIn, amountOut, path, this(address), block.timestamp ); uint256 _actualAmountOut = amounts[1]; uint256 _swapFee = _actualAmountOut.div(100).mul(5); uint256 _baseAmountLeft = _actualAmountOut.sub(_swapFee); _protocolFee.add(_swapFee); _mint(_msgSender(), amountIn); IERC20(_targetToken).approve( address(UniswapV2Router02), _baseAmountLeft.div(2) ); address[] memory path2 = new address[](2); path2[0] = address(_baseToken); path2[1] = this(address); UniswapV2Router02.swapExactTokensForTokens( _baseAmountLeft.div(2), dipAmountOut, path2, this(address), block.timestamp ); // fund the dip/basetoken pool } function dip() public { require(block.timestamp >= _startTime.add(2 days), "Token distribution lasts for two days before the dip."); _predip = false; _calculateShare(_dipPair); IERC20(_baseToken).transfer(_protocolFeeWallet, _protocolFee); } function rebase() public { // adjust total supply up or down based on target token price // uniswap specific things -- sync and skim functions // reward LP token } // set a user's share relative to their percentage of the initial total supply function _calculateShare(address account) internal { require(_predip === false, "The token distribution period is still active."); require(_balances[account] === 0, "Token share has already been calculated for this account."); uint256 share = FixedPoint.calculateMantissa( _balances[account], _initialSupply ); delete _balances[account]; _shares[account] = share; } function _convertAmountToShare(uint256 amount) internal { return FixedPoint.multiplyUintByMantissa( _totalSupply, amount ); } } // protocol fee goes into multisig and address can be updated? // dip LP tokens for specified pairs locked to farm doubledip tokens? // doubledip tokens used to vote on new specified pairs, multisig, and spending? // if share is not calculated for recipient, that's fine, and calling calculateShare will add to their current share from previous postdip transfers // locking dip LP tokens to farm doubledip tokens incentivizes long-term liquidity for important pools // for token distro, amountOut should be calculated at the UI level // amountOut could also be calculated via a Uniswap oracle // this might be simpler from a user experience perspective
fund the dip/basetoken pool
function swap(uint256 amountIn, uint256 amountOut, uint256 dipAmountOut) public { require(_predip === true, "The token distribution period is over."); IERC20(_targetToken).transferFrom(_msgSender(), address(this), amountIn); IERC20(_targetToken).approve(address(UniswapV2Router02), amountIn); address[] memory path = new address[](2); path[0] = address(_targetToken); path[1] = address(_baseToken); uint[] memory amounts = UniswapV2Router02.swapExactTokensForTokens( amountIn, amountOut, path, this(address), block.timestamp ); uint256 _actualAmountOut = amounts[1]; uint256 _swapFee = _actualAmountOut.div(100).mul(5); uint256 _baseAmountLeft = _actualAmountOut.sub(_swapFee); _protocolFee.add(_swapFee); _mint(_msgSender(), amountIn); IERC20(_targetToken).approve( address(UniswapV2Router02), _baseAmountLeft.div(2) ); address[] memory path2 = new address[](2); path2[0] = address(_baseToken); path2[1] = this(address); UniswapV2Router02.swapExactTokensForTokens( _baseAmountLeft.div(2), dipAmountOut, path2, this(address), block.timestamp ); }
12,848,023
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /// @title Describes methods that provide all the information about current governance contract state interface IMooniswapFactoryGovernance { /// @notice Returns information about mooniswap shares /// @return referralShare Referrals share /// @return governanceShare Governance share /// @return governanceWallet Governance wallet address /// @return referralFeeReceiver Fee collector address function shareParameters() external view returns(uint256 referralShare, uint256 governanceShare, address governanceWallet, address referralFeeReceiver); /// @notice Initial settings that contract was created /// @return defaultFee Default fee /// @return defaultSlippageFee Default slippage fee /// @return defaultDecayPeriod Decay period for virtual amounts function defaults() external view returns(uint256 defaultFee, uint256 defaultSlippageFee, uint256 defaultDecayPeriod); /// @notice Same as `defaults` but only returns fee function defaultFee() external view returns(uint256); /// @notice Same as `defaults` but only returns slippage fee function defaultSlippageFee() external view returns(uint256); /// @notice Same as `defaults` but only returns decay period function defaultDecayPeriod() external view returns(uint256); /// @notice Describes previous default fee that had place, current one and time on which this changed function virtualDefaultFee() external view returns(uint104, uint104, uint48); /// @notice Describes previous default slippage fee that had place, current one and time on which this changed function virtualDefaultSlippageFee() external view returns(uint104, uint104, uint48); /// @notice Describes previous default decay amount that had place, current one and time on which this changed function virtualDefaultDecayPeriod() external view returns(uint104, uint104, uint48); /// @notice Same as `shareParameters` but only returns referral share function referralShare() external view returns(uint256); /// @notice Same as `shareParameters` but only returns governance share function governanceShare() external view returns(uint256); /// @notice Same as `shareParameters` but only returns governance wallet address function governanceWallet() external view returns(address); /// @notice Same as `shareParameters` but only returns fee collector address function feeCollector() external view returns(address); /// @notice True if address is current fee collector or was in the past. Otherwise, false function isFeeCollector(address) external view returns(bool); /// @notice True if contract is currently working and wasn't stopped. Otherwise, false function isActive() external view returns (bool); }
Describes methods that provide all the information about current governance contract state
interface IMooniswapFactoryGovernance { function shareParameters() external view returns(uint256 referralShare, uint256 governanceShare, address governanceWallet, address referralFeeReceiver); function defaults() external view returns(uint256 defaultFee, uint256 defaultSlippageFee, uint256 defaultDecayPeriod); function defaultFee() external view returns(uint256); function defaultSlippageFee() external view returns(uint256); function defaultDecayPeriod() external view returns(uint256); function virtualDefaultFee() external view returns(uint104, uint104, uint48); function virtualDefaultSlippageFee() external view returns(uint104, uint104, uint48); function virtualDefaultDecayPeriod() external view returns(uint104, uint104, uint48); function referralShare() external view returns(uint256); function governanceShare() external view returns(uint256); function governanceWallet() external view returns(address); function feeCollector() external view returns(address); function isFeeCollector(address) external view returns(bool); function isActive() external view returns (bool); }
15,883,190
./full_match/4/0xEA32E30BB13d7D0108F8f4FA0C77128A78bFdc23/sources/Poi_flat.sol
This function is no longer recommended for sending Ether.
function sendViaTransfer(address payable _to, uint256 _amount) public payable { _to.transfer(_amount); }
807,018